<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Sku as SkuService;
use app\common\service\Order as OrderService;
use app\common\service\Material as MaterialService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\Stock as StockService;
use app\common\service\StallFeed as StallFeedService;
use app\common\service\StockLog as StockLogService;
use app\common\service\MaterialStock as MaterialStockService;
use app\common\service\MaterialStockUse as MaterialStockUseService;
use app\common\service\DistributingFeed as DistributingFeedService;
use app\common\service\Memo as MemoService;
use app\common\service\Purchasing as PurchasingService;
use think\db\Query;
use app\common\service\MaterialReturn as MaterialReturnService;
use think\Db;
use Endroid\QrCode\QrCode;

/**
 * 采购进度
 */
class Purchasing extends Admin
{

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 采购进度
     *
     * @author KING
     * @date 2020年7月14日
     *
     */
    public function index()
    {
    	$_st = microtime(true)*1000;
    	$factoryKV = getFactoryKV(false);
    	$factoryOutgoKV = getFactoryOutgoKV(null);
    	$systemUserKV = getSystemUserKV(null);
    	$groupKV = getGroupKV(0);
    	$stallsKV = getStallsKV();
    	if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
			//$noStat = $this->request->param('noStat/s','');
			$isAutoImport    = $this->request->param('is_auto_import/d',0);
			$stat = $this->request->param('a/s','');
			$statCondition = $this->request->param('sc/s','');
    		$where      =$detailWhere= $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$factorId      = $this->request->param('factory_id/d', 0);
    		$orderStatus    = $this->request->param('order_status/s','');
    		$clientOrdernum    = $this->request->param('client_ordernum/s','');
    		$sku    = $this->request->param('sku/s','');
    		$createDateRange    = $this->request->param('create_date_range/s','');
    		$overDateRange    = $this->request->param('over_date_range/s','');
    		$caichuangOverDateRange    = $this->request->param('caichuang_over_date_range/s','');
			$orders=$this->request->param('orders/s','');
    		$export     = $this->request->param('export/d', 0);
			$detailWhere=[
				'factory_id'=>$factorId,
				'order_status'=>$orderStatus,
				'client_ordernum'=>$clientOrdernum,
				'sku'=>$sku,
				'create_date_range'=>$createDateRange,
				'over_date_range'=>$overDateRange,
				'caichuang_over_date_range'=>$caichuangOverDateRange,
				'is_auto_import'=>$isAutoImport
			];


    		if ($export) {
    			set_time_limit(0);
    			ini_set('memory_limit', '1024M');
    			$page = 1;
    			$limit = 99999;
    		}
			if ($orders !='') {
				$where[] = ['id', 'in', $orders];
			}
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    $ext_id != '' && $where[] = ['ext_id', '=', $ext_id];
                    break;
            }
			if ($isAutoImport > 0) {
				$where[] = ['is_auto_import', '=', $isAutoImport];
			}
            //订单加一级
            order_level($where,'');
    		if ($factorId) {
    			$where[] = ['factory_id', '=', $factorId];
    		}
    		if ($clientOrdernum == '') {
				$where[] = ['status', '<>', 99];
    		}
    		if ($orderStatus != '') {
    			switch ($orderStatus){
    				case 1:	// 面料采购未完成（未打标）
    					$subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
						$where[] = ['status', 'in', [0,1]];
    					break;
    				case 2:	//辅料采购未完成（未打标）
    					$subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type = 'accessories' and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
						$where[] = ['status', 'in', [0,1]];
    					break;
    				case 3: // 换料中
    					$subQuery = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
						$where[] = ['status', 'in', [0,1,2]];
    					break;
    				case 4: // 批色不通过
    					$subQuery = db('order_material')->where("caigou_show=1 and caigou_status=2")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
						$where[] = ['status', 'in', [0,1,2]];
    					break;
					case 5: // 面料已到料
    					$subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type != 'accessories' and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery})")];
						$where[] = ['status', 'in', [0,1]];
    					break;
					case 6: // 已批色
						$subQuery11 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$subQuery22 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
						$subQuery33 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery11})")];
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery22})")];
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery33})")];

//    					$subQuery = db('order_material')->where("caigou_show=1 and caigou_over_time <> 0")->distinct(true)->field('order_id')->buildSql();
//    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];						//dump($subQuery);
						$where[] = ['status', 'in', [0,1,2]];
    					break;
    			}
				$where[] =['stock_type','not in','10,11'];
    		}

    		if ($clientOrdernum != '') {
    			$where[] = ['client_ordernum','like', "%".$clientOrdernum."%"];
    		}
    		if ($sku != '') {
    			$where[] = ['sku', 'like', "%".$sku."%"];
    		}
    		if ($createDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
    			$where[] = ['create_time', 'between', [$startTime, $endTime+86399]];
    		}
    		if ($overDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $overDateRange));
    			$where[] = ['over_time', 'between', [$startTime, $endTime+86399]];
    		}
    		if ($caichuangOverDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $caichuangOverDateRange));
    			$where[] = ['caichuang_over_time', 'between', [$startTime, $endTime+86399]];
    		}
			if($statCondition!=""){
				switch ($statCondition){
    				case "allCount":	// 全部
    					break;
    				case "fabricCgOverCount":	//面料采购已完成单数
    					$subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
						$subQuery2 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery1})")];
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery2})")];
    					break;
					case "returnMaterialCount":	//退料中
    					$subQuery1 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery1})")];
    					break;
    				case "fabricCgNotCount": // 面料采购未完成单
    					$subQuery1=db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
						$subQuery2 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery1})")];
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery2})")];
    					break;
    				case "apColorOverCount": // 已批色单数
    					$subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
						$subQuery3 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery1})")];
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery2})")];
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery3})")];
    					break;
					case "apColorNotCount": // 未批色单数
						$subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery1})")];
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery2})")];

    					break;
					case "apColorNoCount": // 批色不通过单数
						$subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
						$subQuery3 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery1})")];
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery2})")];
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery3})")];
    					$subQuery4 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=2")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery4})")];

    					break;
					case "ckClothSkOverCount": // 已验布缩水的单数
    					$subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery1})")];
    					$subQuery2 = db('order_material_item omi')->join('order_material om', "omi.order_material_id=om.mid", 'left')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and omi.is_return=0 and om.caigou_show=1 and ((om.need_checkcloth=1 and omi.is_checkcloth=0) or (om.need_shrink=1 and omi.is_shrink=0))")->distinct(true)->field('om.order_id')->buildSql();
						$subQuery3 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery2})")];
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery3})")];
    					break;
					case "ckClothSkNotCount": //未验布缩水的单数=面料采购已完成单-已验布缩水的单数
						$subQuery1 = db('order_material_item omi')->join('order_material om', "omi.order_material_id=om.mid", 'left')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and omi.is_return=0 and om.caigou_show=1 and ((om.need_checkcloth=1 and omi.is_checkcloth=0) or (om.need_shrink=1 and omi.is_shrink=0))")->distinct(true)->field('om.order_id')->buildSql();
						$subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery2})")];
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery1})")];

    					break;
					case "caichuangOverCount": // 已裁床单数
    					$subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
						$subQuery3 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery1})")];
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery2})")];
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery3})")];
						$where[] = ['caichuang_over_time', '<>', 0];

    					break;
					case "caichuangNotCount": ////未裁床单数=批色完成-已裁床单数
						$subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery1})")];
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery2})")];
						$subQuery3 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=2")->distinct(true)->field('om.order_id')->buildSql();
						$subQuery4 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery3})")];
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery4})")];
    					$where[] = ['caichuang_over_time', '=', 0];
    					break;
					case "acOverCount": // 辅料发放单数
						$subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
						$subQuery4 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery1})")];
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery2})")];
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery4})")];
						$where[] = ['caichuang_over_time', '<>', 0];
    					$subQuery3 = db('distributing')->where("status in (1,2,3)")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery3})")];
    					break;
					case "acNotCount": // 辅料未发放单数
						$subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$subQuery2 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
						$subQuery4 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery1})")];
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery2})")];
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery4})")];
						$where[] = ['caichuang_over_time', '<>', 0];
    					$subQuery3 = db('distributing')->where("status in (1,2,3)")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery3})")];
    					break;
					case "acNoCount": //辅料采购未完成
						$subQuery1 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type = 'accessories' and om.caigou_show=1 and om.is_caigou_start!=2")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery1})")];
						$where[] = ['status', 'in', [0,1]];
    					break;
				}
				$where[] = ['stock_type', 'not in', '10,11'];
			}
    		$data['count'] = db('order')->where($where)->count('id');
			$data['skuCount']=count(db('order')->where($where)->distinct(true)->column('sku'));
			$data['allQuantity']=db('order')->where($where)->value('sum(quantity)');
    		$order = "FIELD(status,2,99) ASC,caigou_status ASC, create_time ASC";
    		$list = db('order')->where($where)->page($page)->limit($limit)->orderRaw($order)->select();
    		$skuService = new SkuService();
    		$orderSizeService = new OrderSizeService();
    		$orderMaterialService = new OrderMaterialService();
    		$stockService = new StockService();
			$stockLogService = new StockLogService();
    		$materialStockService = new MaterialStockService();
    		$materialStockUseService = new MaterialStockUseService();
    		$distributingFeedService = new DistributingFeedService();
			$purchasingService = new PurchasingService();
    		foreach ($list as $k => $v) {
    			$osList = $orderSizeService->getListByOrderId($v['id']);

    			$list[$k]['osList'] = $osList;
    			$list[$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'jiaohuo_tail_count' => array_sum(array_column($osList, 'jiaohuo_tail_count')), 'delivery_count' => array_sum(array_column($osList, 'delivery_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
    			$list[$k]['shipment_time_diff'] = $v['status'] == 2 ? formatSecond($v['shipment_time'] - $v['over_time']) : formatSecond($v['shipment_time'] - time());
    			$list[$k]['create_time_diff'] = $v['status'] == 2 ? formatSecond($v['over_time'] - $v['shipment_time']) : formatSecond(time() - $v['shipment_time']);
    			$list[$k]['o_type_text'] = arrayGet(config('mimo.order_otype'), $v['o_type'], '');
    			$list[$k]['delete_text'] = $v['status'] == 99 ? '已废除' : '';
    			$list[$k]['sInfo'] = $skuService->getInfoBySku($v['sku']);
    			$list[$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
                $list[$k]['skuStock']=$skuService->getSkuStockBySku($v['sku'],$v['factory_id']);
    			$list[$k]['group_name'] = arrayGet($groupKV, $v['group_id'], '');
    			$list[$k]['factory_outgo_name'] = arrayGet($factoryOutgoKV, $v['factory_outgo_id'], '');
    			$list[$k]['caichuang_user_name'] = arrayGet($systemUserKV, $v['caichuang_user_id'], '');
    			$list[$k]['caigou_user_name'] = arrayGet($systemUserKV, $v['caigou_user_id'], '');

    			$omList = $orderMaterialService->getListByOrderId($v['id']);
				if ($export) {
					if(!$omList) unset($v);
				}

    			foreach ($omList as $sk => $sv) {
    				if ($sv['caigou_show'] == 0) {
    					unset($omList[$sk]); // 去除不在采购进度显示条目
    					continue;
    				}
					$omList[$sk]['factory_id']=$v['factory_id'];
					$omList[$sk]['jing_material_dosage'] = round($v['quantity'] * $sv['material_dosage'], 2);
    				$omList[$sk]['total_material_dosage'] = round(($v['quantity'] * $sv['material_dosage'])+($v['quantity'] * $sv['material_dosage'])*$sv['loss']/100, 2);

    				// 余料使用
    				if (arrayGet($sv['mInfo'], 'type') == 'accessories') {
    					$omList[$sk]['stock_use_num'] = $stockLogService->getUseNum($sv['material_id'], $sv['order_id']);
    				} else {
    					$applyAndUsed = $materialStockUseService->getApplyAndUsed($sv['material_id'], $sv['order_id']);
    					//$metreLeftInfo = $materialStockService->checkMetreLeft($sv['material_id']);
    					//$omList[$sk]['check_metre_left'] = $metreLeftInfo;
    					$omList[$sk]['apply_and_used'] = $applyAndUsed;
    				}

    				// 采购状态
    				if (arrayGet($sv['mInfo'], 'type') == 'accessories') {
    					$omList[$sk]['check_ing'] = $distributingFeedService->checkIng($sv['material_id'], $sv['order_id']);
    				} else {
    					$omList[$sk]['metre_left'] = $materialStockService->getMetreLeft($sv['material_id']);
    				}

    				// 余料使用量
    				if (arrayGet($sv['mInfo'], 'type') == 'accessories') {
    					$omList[$sk]['stock_left'] = $stockService->getStockLeft($sv['material_id']);
    				}

    				// 物料状态
    				$omList[$sk]['material_status'] = $orderMaterialService->getMaterialStatus($sv['mid']);
					$omList[$sk]['sku'] = $v['sku'];
    			}

    			sort($omList);
    			$list[$k]['omList'] = $omList;
    		}

    		if ($export) {
    			$this->_exportXls('采购进度-' .date('YmdHis'), $list,$stat);
    			exit;
    		}

    		$data['data'] = $list;
    		$data['code'] = 0;
    		$data['msg'] = '';
			// 订单进度统计
			if ($page == 1 && $stat=="") {
				$data['stat'] = $purchasingService->getPurchasingStat(FACTORY_IDS,$where,$detailWhere);
			}
    		$_et = microtime(true)*1000;
    		$data['time'] = $_et-$_st;

    		return json($data);
    	}

    	$assign = [
    		'factoryKV' => [0 => '请选择'] + $factoryKV,
    		'stallsKV' => $stallsKV,
            'orderFrom' => [0 => '请选择'] + config('mimo.order_from'),
    		'systemUserKV' => $systemUserKV,
    		'purchasingUserKV' => [0 => '请选择'] + getTagUserKV('tag_purchasing_user'),
    	];
    	return $this->assign($assign)->fetch();
    }

	/**
	 * 时效统计
	 *
	 * @author King
	 * @date 2021年9月17日
	 *
	 * @return \think\response\Json
	 */
	public function timeStatistics(){
		if ($this->request->isAjax()) {
			$isAutoImport    = $this->request->param('is_auto_import/d',0);
			$stat = $this->request->param('a/s','');
			$statCondition = $this->request->param('sc/s','');
			$where      =$detailWhere= $data = [];
			$page       = $this->request->param('page/d', 1);
			$limit      = $this->request->param('limit/d', 20);
			$factorId      = $this->request->param('factory_id/d', 0);
			$orderStatus    = $this->request->param('order_status/s','');
			$clientOrdernum    = $this->request->param('client_ordernum/s','');
			$sku    = $this->request->param('sku/s','');
			$createDateRange    = $this->request->param('create_date_range/s','');
			$overDateRange    = $this->request->param('over_date_range/s','');
			$caichuangOverDateRange    = $this->request->param('caichuang_over_date_range/s','');
			if ($isAutoImport > 0) {
				$where[] = ['is_auto_import', '=', $isAutoImport];
			}

            //订单加一级
            order_level($where,'');
    		if ($factorId) {
    			$where[] = ['factory_id', '=', $factorId];
    		}
			$where[] = ['status', 'in', [0,1,2]];
			$where[] = ['status', '<>', 99];
			if ($orderStatus != '') {
    			switch ($orderStatus){
    				case 1:	// 面料采购未完成（未打标）
    					$subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
						$where[] = ['status', 'in', [0,1]];
    					break;
    				case 2:	//辅料采购未完成（未打标）
    					$subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type = 'accessories' and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
						$where[] = ['status', 'in', [0,1]];
    					break;
    				case 3: // 换料中
    					$subQuery = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
						$where[] = ['status', 'in', [0,1,2]];
    					break;
    				case 4: // 批色不通过
    					$subQuery = db('order_material')->where("caigou_show=1 and caigou_status=2")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
						$where[] = ['status', 'in', [0,1,2]];
    					break;
					case 5: // 面料已到料
    					$subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type != 'accessories' and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery})")];
						$where[] = ['status', 'in', [0,1,2]];
    					break;
					case 6: // 已批色
						$subQuery11 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$subQuery22 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
						$subQuery33 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery11})")];
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery22})")];
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery33})")];
						$where[] = ['status', 'in', [0,1,2]];
    					break;
    			}

    		}

    		if ($clientOrdernum != '') {
    			$where[] = ['client_ordernum','like', "%".$clientOrdernum."%"];
    		}
    		if ($sku != '') {
    			$where[] = ['sku', 'like', "%".$sku."%"];
    		}
    		if ($createDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
    			$where[] = ['create_time', 'between', [$startTime, $endTime+86399]];
    		}
    		if ($overDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $overDateRange));
    			$where[] = ['over_time', 'between', [$startTime, $endTime+86399]];
    		}
    		if ($caichuangOverDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $caichuangOverDateRange));
    			$where[] = ['caichuang_over_time', 'between', [$startTime, $endTime+86399]];
    		}
			$where[] =['stock_type','not in','10,11'];
			$order = "FIELD(status,2,99) ASC,caigou_status ASC, create_time ASC";
			$list=0;
    		$list = db('order')->where($where)->orderRaw($order)->column('id');
			$asingOrder=db('aging_order')->where('order_id','in',$list)->select();
			$allOrder= array_column($asingOrder, 'order_id');
			$asingOrderCount=db('aging_order')->where('order_id','in',$list)->count();
			$dayAll=['day_caigou','day_caichuang_before','day_caichuang','day_chejian_before'];
			foreach ($dayAll as $keyd => $valued) {
				$order=[];
				$arr=array_column($asingOrder,$valued);$order=array_column($asingOrder,$valued,'order_id');//把值提取出来转成一维数组
				$arr=array_count_values($arr);
				foreach ($order as $ko => $vo) {
					$orders[$valued][$vo][]=$ko;
				}
				$day1=$day2=$day3=$day4=$dayThan4=0;
				$allDay=$order2=$order3=$order4=$order1=$orderThan4=[];
				foreach ($arr as $kk => $vv) {
					$allDay[]=$kk*$vv;
					if($kk>0&&$kk<=1){
						$day1=$day1+$vv;
						$order1=array_merge($order1,$orders[$valued][$kk]);
					}
					if ($kk>0&&$kk<=2) {
						$day2=$day2+$vv;
						$order2=array_merge($order2,$orders[$valued][$kk]);
					}
					if ($kk>0&&$kk<=3) {
						$day3=$day3+$vv;
						$order3=array_merge($order3,$orders[$valued][$kk]);
					}
					if ($kk>0&&$kk<=4) {
						$day4=$day4+$vv;
						$order4=array_merge($order4,$orders[$valued][$kk]);
					}
					if ($kk>4) {
						$dayThan4=$dayThan4+$vv;
						$orderThan4=array_merge($orderThan4,$orders[$valued][$kk]);
					}
				}
				switch ($valued) {
					case "day_caigou":
						$caiGouWhere=[
							['order_id', 'in', $list],
							['create_time|arrive_time','=',0]
						];
						$notCompleteOrder=db('aging_order')->where($caiGouWhere)->column('order_id');
						$notCompleteCount= count($notCompleteOrder);
						break;
					case "day_caichuang_before":
						$caichuangBeforeWhere=[
							['order_id', 'in', $list],
							['create_time|caichuang_can_do_time','=',0]
						];
						$notCompleteOrder=db('aging_order')->where($caichuangBeforeWhere)->column('order_id');
						$notCompleteCount= count($notCompleteOrder);
						break;
					case "day_caichuang":
						$caichuangWhere=[
							['order_id', 'in', $list],
							['caichuang_can_do_time|caichuang_over_time','=',0]
						];
						$notCompleteOrder=db('aging_order')->where($caichuangWhere)->column('order_id');
						$notCompleteCount= count($notCompleteOrder);
						break;
					case "day_chejian_before":
						$chejianBeforeWhere=[
							['order_id', 'in', $list],
							['create_time|caichuang_over_time','=',0]
						];
						$notCompleteOrder=db('aging_order')->where($chejianBeforeWhere)->column('order_id');
						$notCompleteCount= count($notCompleteOrder);
						break;
				}
				$dayCount=array_sum($arr);
				$aveDay=$dayCount!=0?round(array_sum($allDay)/$dayCount,2):0;
				$order1=$order1!=[]?$order1:[0];
				$order2=$order2!=[]?$order2:[0];
				$order3=$order3!=[]?$order3:[0];
				$order4=$order4!=[]?$order4:[0];
				$orderThan4=$orderThan4!=[]?$orderThan4:[0];

				//$notCompleteOrder=array_merge(array_diff($allOrder,$order4,$orderThan4));

				$dayNumAll[$valued]=['oneDay'=>$day1,'twoDay'=>$day2,'threeDay'=>$day3,'fourDay'=>$day4,'thanFourDay'=>$dayThan4,'dayCount'=>$dayCount,'aveDay'=>$aveDay,'order1'=>$order1,'order2'=>$order2,'order3'=>$order3,'order4'=>$order4,'orderThan4'=>$orderThan4,'notCompleteCount'=>$notCompleteCount,'notCompleteOrder'=>$notCompleteOrder,'count'=>$list];
			}
			unset($asingOrder);

			//物料时效开始计算
			$agingMaterial=db('aging_material')->where('order_id','in',$list)->select();
			$allOrderMaterial= array_column($agingMaterial, 'order_material_id');
			$agingMaterialCount=db('aging_material')->where('order_id','in',$list)->count();
			$allTime=$arrmt=$arrft=$arrat=$arrtap=$arrtch=$arrtsh=[];
			$agingMaterialType=['fabric'=>[],'accessories'=>[]];
			foreach ($agingMaterial as $key => $value) {
				$agingMaterialType[$value['material_type']][]=$value;
			}
			if(isset($agingMaterialType['lining'])){
				$agingMaterialType['fabric']=array_merge($agingMaterialType['fabric'],$agingMaterialType['lining']);
			}
			$arrmt=array_column($agingMaterialType['fabric'],'time_make_tag');//把值提取出来转成一维数组
			$arrmt=array_count_values($arrmt);
			$arrat=array_column($agingMaterialType['accessories'],'time_make_tag');//把值提取出来转成一维数组
			$arrat=array_count_values($arrat);
			$arrtap=array_column($agingMaterial,'time_approval_color');//把值提取出来转成一维数组
			$arrtap=array_count_values($arrtap);
			$arrtch=array_column($agingMaterial,'time_checkcloth');//把值提取出来转成一维数组
			$arrtch=array_count_values($arrtch);
			$arrtsh=array_column($agingMaterial,'time_shrink');//把值提取出来转成一维数组
			$arrtsh=array_count_values($arrtsh);

			$TimeAll=['fabric_make_tag'=>$arrmt,'accessories_make_tag'=>$arrat,'time_approval_color'=>$arrtap,'time_checkcloth'=>$arrtch,'time_shrink'=>$arrtsh];
			foreach ($TimeAll as $keyt => $valuet) {
				$time12=$time24=$time36=$time48=$thanTime48=0;
				if($keyt=="fabric_make_tag" ){
					$orderMaterial=array_column($agingMaterialType['fabric'],'time_make_tag','order_material_id');
					$allOrderMaterial=array_column($agingMaterialType['fabric'],'order_material_id');
					$orderMaterials=[];
					foreach ($orderMaterial as $km => $vm) {
						$orderMaterials[$keyt][$vm][]=$km;
					}
				}elseif($keyt=="accessories_make_tag"){
					$orderMaterial=array_column($agingMaterialType['accessories'],'time_make_tag','order_material_id');
					$allOrderMaterial=array_column($agingMaterialType['accessories'],'order_material_id');
					$orderMaterials=[];
					foreach ($orderMaterial as $km => $vm) {
						$orderMaterials[$keyt][$vm][]=$km;
					}
				}else{
					$orderMaterial=array_column($agingMaterial,$keyt,'order_material_id');
					$allOrderMaterial=array_column($agingMaterial,'order_material_id');
					$orderMaterials=[];
					foreach ($orderMaterial as $km => $vm) {
						$orderMaterials[$keyt][$vm][]=$km;
					}
				}
				$time12=$time24=$time36=$time48=$thanTime48=0;
				$allTime=$materialOrders12=$materialOrders24=$materialOrders36=$materialOrders48=$materialOrdersThan48=$materialOrder12=$materialOrder24=$materialOrder36=$materialOrder48=$materialOrderThan48=[0];
				foreach ($valuet as $k => $v) {
					$allTime[]=$k*$v;
					if($k>0 && $k<=12){
						$time12=$time12+$v;
						$materialOrder12=array_merge($materialOrder12,$orderMaterials[$keyt][$k]);
						$materialOrders12=db('order_material')->where('mid','in',$materialOrder12)->column('order_id');
					}
					if ($k>0 && $k<=24) {
						$time24=$time24+$v;
						$materialOrder24=array_merge($materialOrder24,$orderMaterials[$keyt][$k]);
						$materialOrders24=db('order_material')->where('mid','in',$materialOrder24)->column('order_id');
					}
					if ($k>0 && $k<=36) {
						$time36=$time36+$v;
						$materialOrder36=array_merge($materialOrder36,$orderMaterials[$keyt][$k]);
						$materialOrders36=db('order_material')->where('mid','in',$materialOrder36)->column('order_id');
					}
					if ($k>0 && $k<=48) {
						$time48=$time48+$v;
						$materialOrder48=array_merge($materialOrder48,$orderMaterials[$keyt][$k]);
						$materialOrders48=db('order_material')->where('mid','in',$materialOrder48)->column('order_id');
					}
					if ($k>48) {
						$thanTime48=$thanTime48+$v;
						$materialOrderThan48=array_merge($materialOrderThan48,$orderMaterials[$keyt][$k]);
						$materialOrdersThan48=db('order_material')->where('mid','in',$materialOrderThan48)->column('order_id');
					}
				}
				switch ($keyt) {
					case "fabric_make_tag":
						$caiGouWhere=[
							['order_id', 'in', $list],
							['make_tag_time|arrive_time','=',0],
							['material_type','=','fabric|lining']
						];
						$notCompleteMaterialOrders=db('aging_material')->where($caiGouWhere)->column('order_id');
						$notCompleteMaterialCount= count($notCompleteMaterialOrders);
						break;
					case "accessories_make_tag":
						$caichuangBeforeWhere=[
							['order_id', 'in', $list],
							['make_tag_time|arrive_time','=',0],
							['material_type','=','accessories']
						];
						$notCompleteMaterialOrders=db('aging_material')->where($caichuangBeforeWhere)->column('order_id');
						$notCompleteMaterialCount= count($notCompleteMaterialOrders);
						break;
					case "time_approval_color":
						$caichuangWhere=[
							['order_id', 'in', $list],
							['approval_color_time|arrive_time','=',0]
						];
						$notCompleteMaterialOrders=db('aging_material')->where($caichuangWhere)->column('order_id');
						$notCompleteMaterialCount= count($notCompleteMaterialOrders);
						break;
					case "time_checkcloth":
						$checkclothWhere=[
							['order_id', 'in', $list],
							['checkcloth_time|arrive_time','=',0],
							['is_checkcloth','<>',0]
						];

						$notCompleteMaterialOrders=db('aging_material')->where($checkclothWhere)->column('order_id');
						$notCompleteMaterialCount= count($notCompleteMaterialOrders);
						break;
					case "time_shrink":
						$orderList=implode(",", $list)?implode(",", $list):0;
						$notCompleteMaterialOrders=db('aging_material')->where("order_id in ({$orderList}) and is_shrink <> 0 and ((is_checkcloth=0 and (arrive_time=0 or shrink_time=0)) or (is_checkcloth <> 0 and (checkcloth_time=0 or shrink_time=0)))")->column('order_id');
						$notCompleteMaterialCount= count($notCompleteMaterialOrders);
						break;
				}
				$timeCount=array_sum($valuet);
				$aveHour=$timeCount!=0?round(array_sum($allTime)/$timeCount,2):0;
				//$notCompleteMaterialCount=$timeCount-$time48-$thanTime48;
				//$notCompleteMaterialOrder=array_diff($allOrderMaterial,$materialOrder48,$materialOrderThan48);
				//$notCompleteMaterialOrders=db('order_material')->where('mid','in',$notCompleteMaterialOrder)->column('order_id');
				$timeNumAll[$keyt]=['time12'=>$time12,'time24'=>$time24,'time36'=>$time36,'time48'=>$time48,'thanTime48'=>$thanTime48,'timeCount'=>$timeCount,'aveHour'=>$aveHour,'materialOrder12'=>$materialOrders12,'materialOrder24'=>$materialOrders24,'materialOrder36'=>$materialOrders36,'materialOrder48'=>$materialOrders48,'materialOrdeThan48'=>$materialOrdersThan48,'notCompleteMaterialCount'=>$notCompleteMaterialCount,'notCompleteMaterialOrder'=>$notCompleteMaterialOrders];
			}
			$data=['order'=>$dayNumAll,'material'=>$timeNumAll];
			return json($data);
		}

	}

	/**
	 * 财务时效统计
	 */
	public function cwTimeStatistics(){
		if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
			$isAutoImport    = $this->request->param('is_auto_import/d',0);
			$stat = $this->request->param('a/s','');
			$statCondition = $this->request->param('sc/s','');
			$where      =$detailWhere= $data = [];
			$page       = $this->request->param('page/d', 1);
			$limit      = $this->request->param('limit/d', 20);
			$factorId      = $this->request->param('factory_id/d', 0);
			$orderStatus    = $this->request->param('order_status/s','');
			$clientOrdernum    = $this->request->param('client_ordernum/s','');
			$sku    = $this->request->param('sku/s','');
			$createDateRange    = $this->request->param('create_date_range/s','');
			$overDateRange    = $this->request->param('over_date_range/s','');
			$caichuangOverDateRange    = $this->request->param('caichuang_over_date_range/s','');
			if ($isAutoImport > 0) {
				$where[] = ['is_auto_import', '=', $isAutoImport];
			}

            //订单加一级
            order_level($where,'');
    		if ($factorId) {
    			$where[] = ['factory_id', '=', $factorId];
    		}
			$where[] = ['status', 'in', [0,1,2]];
			$where[] = ['status', '<>', 99];
			if ($orderStatus != '') {
    			switch ($orderStatus){
    				case 1:	// 面料采购未完成（未打标）
    					$subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
						$where[] = ['status', 'in', [0,1]];
    					break;
    				case 2:	//辅料采购未完成（未打标）
    					$subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type = 'accessories' and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
						$where[] = ['status', 'in', [0,1]];
    					break;
    				case 3: // 换料中
    					$subQuery = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
						$where[] = ['status', 'in', [0,1,2]];
    					break;
    				case 4: // 批色不通过
    					$subQuery = db('order_material')->where("caigou_show=1 and caigou_status=2")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
						$where[] = ['status', 'in', [0,1,2]];
    					break;
					case 5: // 面料已到料
    					$subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type != 'accessories' and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery})")];
						$where[] = ['status', 'in', [0,1,2]];
    					break;
					case 6: // 已批色
						$subQuery11 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.is_make_tag=0")->distinct(true)->field('om.order_id')->buildSql();
    					$subQuery22 = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("m.type in ('fabric', 'lining') and om.caigou_show=1 and om.caigou_status=0")->distinct(true)->field('om.order_id')->buildSql();
						$subQuery33 = db('material_return')->where("status=1")->distinct(true)->field('order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery11})")];
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery22})")];
						$where[] = ['id', 'exp', Db::raw("not in({$subQuery33})")];
						$where[] = ['status', 'in', [0,1,2]];
    					break;
    			}

    		}
    		if ($clientOrdernum != '') {
    			$where[] = ['client_ordernum','like', "%".$clientOrdernum."%"];
    		}
    		if ($sku != '') {
    			$where[] = ['sku', 'like', "%".$sku."%"];
    		}
    		if ($createDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
    			$where[] = ['create_time', 'between', [$startTime, $endTime+86399]];
    		}
    		if ($overDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $overDateRange));
    			$where[] = ['over_time', 'between', [$startTime, $endTime+86399]];
    		}
    		if ($caichuangOverDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $caichuangOverDateRange));
    			$where[] = ['caichuang_over_time', 'between', [$startTime, $endTime+86399]];
    		}
			$where[] =['stock_type','not in','10,11'];
			$order = "FIELD(status,2,99) ASC,caigou_status ASC, create_time ASC";
    		$list = db('order')->where($where)->orderRaw($order)->column('id');
			$asingOrder=db('aging_order')->where('order_id','in',$list)->select();
			$dayAll=['day_caigou','day_checkcloth','day_shrink','day_caichuang_before','day_caichuang','day_chejian_before'];
			foreach ($dayAll as $keyd => $valued) {
				$order=[];
				$arr=array_column($asingOrder,$valued);$order=array_column($asingOrder,$valued,'order_id');//把值提取出来转成一维数组
				$arr=array_count_values($arr);
				foreach ($order as $ko => $vo) {
					$orders[$valued][$vo][]=$ko;
				}//dump($orders);
				$day1=$day2=$day3=$day4=$dayThan4=0;
				$allDay=$arrft=$arrat=$arrmt=$arrlt=$arrtap=$order2=$order3=$order4=$order1=$orderThan4=[];
				foreach ($arr as $kk => $vv) {
					$allDay[]=$kk*$vv;

//					if($kk>0&&$kk<=1){
//						$day1=$vv;
//						$order1=$orders[$valued][$kk];
//					}
//					if ($kk>0&&$kk<=2) {
//						$day2=$vv;
//						$order2=$orders[$valued][$kk]+$order1;
//					}
//					if ($kk>0&&$kk<=3) {
//						$day3=$vv;
//						$order3=$orders[$valued][$kk]+$order2;
//					}
//					if ($kk>0&&$kk<=4) {
//						$day4=$vv;
//						$order4=$orders[$valued][$kk]+$order3;
//					}
//					if ($kk>4) {
//						$dayThan4=$vv;
//						foreach ($orders[$valued] as $kt => $vt) {
//							if($kt>4) $orderThan4=$orderThan4+$vt;
//						}
//					}
				}

				$dayCount=array_sum($arr);
				$aveDay=$dayCount!=0?round(array_sum($allDay)/$dayCount,2):0;
				$order1=$order1!=[]?$order1:[0];
				$order2=$order2!=[]?$order2:[0];
				$order3=$order3!=[]?$order3:[0];
				$order4=$order4!=[]?$order4:[0];
				$orderThan4=$orderThan4!=[]?$orderThan4:[0];
				$dayNumAll[$valued]=['oneDay'=>$day1,'twoDay'=>$day2,'threeDay'=>$day3,'fourDay'=>$day4,'thanFourDay'=>$dayThan4,'dayCount'=>$dayCount,'aveDay'=>$aveDay,'order1'=>$order1,'order2'=>$order2,'order3'=>$order3,'order4'=>$order4,'orderThan4'=>$orderThan4];
			}
			$agingMaterial=db('aging_material')->where('order_id','in',$list)->select();
			foreach ($agingMaterial as $key => $value) {
				$agingMaterialType[$value['material_type']][]=$value;
			}
			if(isset($agingMaterialType['fabric'])){
				$arrft=array_column($agingMaterialType['fabric'],'time_make_tag');//把值提取出来转成一维数组
			}
			if(isset($agingMaterialType['lining'])){
				$arrlt=array_column($agingMaterialType['lining'],'time_make_tag');
			}
			$arrmt=array_merge($arrft,$arrlt);
			$arrmt=array_count_values($arrmt);
			if(isset($agingMaterialType['accessories'])){
				$arrat=array_column($agingMaterialType['accessories'],'time_make_tag');//把值提取出来转成一维数组
				$arrat=array_count_values($arrat);
			}
			$arrtap=array_column($agingMaterial,'time_approval_color');//把值提取出来转成一维数组
			$arrtap=array_count_values($arrtap);
			$arrtch=array_column($agingMaterial,'time_checkcloth');//把值提取出来转成一维数组
			$arrtch=array_count_values($arrtch);
			$arrtsh=array_column($agingMaterial,'time_shrink');//把值提取出来转成一维数组
			$arrtsh=array_count_values($arrtsh);

			$TimeAll=['fabric_make_tag'=>$arrmt,'accessories_make_tag'=>$arrat,'time_approval_color'=>$arrtap,'time_checkcloth'=>$arrtch,'time_shrink'=>$arrtsh];
			foreach ($TimeAll as $key => $value) {
				$time12=$time24=$time36=$time48=$thanTime48=0;
//				if($key==''){
//					$orderMaterial=array_column($agingMaterial,$valued,'order_id');
//					$orderMaterials=[];
//					foreach ($order as $ko => $vo) {
//						$orderMaterials[$valued][$vo][]=$ko;
//					}//dump($orderMaterials);
//				}

				foreach ($value as $k => $v) {
					$allTime[]=$k*$v;
					if($k>0 && $k<=12){
						$time12=$time12+$v;
					}
					if ($k>0 && $k<=24) {
						$time24=$time24+$v;
					}
					if ($k>0 && $k<=36) {
						$time36=$time36+$v;
					}
					if ($k>0 && $k<=48) {
						$time48=$time48+$v;
					}
					if ($k>48) {
						$thanTime48=$thanTime48+$v;
					}
				}
				$timeCount=array_sum($value);
				$aveHour=$timeCount!=0?round(array_sum($allTime)/$timeCount,2):0;
				$timeNumAll[$key]=['time12'=>$time12,'time24'=>$time24,'time36'=>$time36,'time48'=>$time48,'thanTime48'=>$thanTime48,'timeCount'=>$timeCount,'aveHour'=>$aveHour];
			}

			$data=['order'=>$dayNumAll,'material'=>$timeNumAll];
			return json($data);
		}


	}
    /**
     * 导出xls
     *
     * @author KING date 2020年08月11日
     *
     * @param string $fileName
     * @param array $data
     */
    private function _exportXls($fileName, $data, $stat) {
    	$head = ['客户订单号','SKU','图片','总数','采购执行人','材料名称','材料SKU','供应商','型号','单件用量','批色时间','采购量','采购单位','单价','实际采购量','条数'];

    	$phpExcel = getExcelObj();
    	$sheet = $phpExcel->setActiveSheetIndex(0);
		$objDate = new \PHPExcel_Shared_Date();
		$objFormat = new \PHPExcel_Style_NumberFormat();
    	// 表头处理
    	foreach ($head as $k => $v) {
    		$cellKey = getExcelLetter($k);
    		$sheet->getColumnDimension($cellKey)->setWidth(20);
    		$sheet->setCellValue($cellKey . "1", $v);
    		$sheet->getRowDimension(1)->setRowHeight(30);
    		$sheet->getStyle($cellKey . "1")->getFont()->setBold(true);
    		$sheet->getStyle($cellKey . "1")->getAlignment()->setVertical('center');
    		$sheet->getStyle($cellKey . "1")->getFont()->getColor()->setARGB("FF0000FF");
    	}

    	$skuService = new SkuService();
    	require_once env('root_path').'plugins/excel/phpexcel/Classes/PHPExcel/Worksheet/Drawing.php';

    	$row = 2; // 当前行
    	$n = 0;
    	foreach ($data as $k => $v) {
    		if (count($v['omList']) > 1) {
    			$endCol = $row + count($v['omList']) - 1;
    			$sheet->mergeCells('A' . $row . ':A' . $endCol);
    			$sheet->mergeCells('B' . $row . ':B' . $endCol);
    			$sheet->mergeCells('C' . $row . ':C' . $endCol);
    			$sheet->mergeCells('D' . $row . ':D' . $endCol);
    			$sheet->mergeCells('E' . $row . ':E' . $endCol);
    		}

    		$sheet->getStyle('A' . $row)->getAlignment()->setVertical('center');
    		$sheet->getStyle('B' . $row)->getAlignment()->setVertical('center');
    		$sheet->getStyle('C' . $row)->getAlignment()->setVertical('center');
    		$sheet->getStyle('D' . $row)->getAlignment()->setVertical('center');
    		$sheet->getStyle('E' . $row)->getAlignment()->setVertical('center');

    		$sheet->setCellValueExplicit('A' . $row, $v['client_ordernum'], 'n');
    		$sheet->setCellValueExplicit('B' . $row, $v['sku'], 's');

    		// 图片
    		$cellVal = $skuService->getPicBySku($v['sku'], false);
    		if ($cellVal && env('env')=='production' && stripos($cellVal, IMG_URL) !== false && $stat=="") {
    			$sheet->getRowDimension($row)->setRowHeight(100);
    			$cellVal = env('root_path') . 'public/' . str_replace(IMG_URL, "", $cellVal);

    			$objDrawing = new \PHPExcel_Worksheet_Drawing();
    			// 设置图片路径 切记：只能是本地图片
    			$objDrawing->setPath($cellVal);
    			// 设置图片高度
    			$objDrawing->setWidth(100);
    			// $objDrawing->setHeight(80);
    			// 设置图片要插入的单元格
    			$objDrawing->setCoordinates('C' . $row);
    			// 设置图片所在单元格的格式
    			$objDrawing->setOffsetX(0);
    			$objDrawing->setRotation(0);
    			$objDrawing->getShadow()->setVisible(false);
    			$objDrawing->setWorksheet($sheet);
    		} else {
    			$sheet->setCellValueExplicit('C' . $row, '', 's');
    		}

    		// 总数
    		$sheet->setCellValueExplicit('D' . $row, "总数：" . $v['quantity'], 'n');
    		$sheet->getStyle('D' . $row)->getAlignment()->setWrapText(TRUE);
    		$sheet->setCellValueExplicit('E' . $row, $v['caigou_user_name'], 's');

    		foreach ($v['omList'] as $sk => $sv) {
    			//$sheet->getRowDimension($row)->setRowHeight(22);

    			$sheet->setCellValueExplicit('F' . $row, arrayGet($sv['mInfo'], 'name', ''), 's');
                $sheet->setCellValueExplicit('G' . $row, arrayGet($sv['mInfo'], 'material_sku', ''), 's');
                $sheet->setCellValueExplicit('H' . $row, arrayGet($sv['mInfo'], 'supplier', ''), 's');
    			$sheet->setCellValueExplicit('I' . $row, arrayGet($sv['mInfo'], 'model', ''), 's');

    			// 单件用量
    			$sheet->setCellValueExplicit('J' . $row, $sv['material_dosage'], 'n');
				// 批色时间
    			//$sheet->setCellValueExplicit('J' . $row, $sv['caigou_over_time'] > 0 ? date('Y-m-d H:i:s', $sv['caigou_over_time']) : 's');
				if($sv['caigou_over_time'] > 0){
					$phpExcel->getActiveSheet()->setCellValue('K' . $row, $objDate::PHPToExcel($sv['caigou_over_time']));
					$phpExcel->getActiveSheet()->getStyle('K' . $row)->getNumberFormat()->setFormatCode($objFormat::FORMAT_DATE_XLSX22);
				}else{
					$sheet->setCellValueExplicit('K' . $row,'');
				}
    			// 采购量
    			$sheet->setCellValueExplicit('L' . $row, round($v['quantity'] * $sv['material_dosage'], 2), 'n');

    			// 采购单位
    			$sheet->setCellValueExplicit('M' . $row, arrayGet($sv['mInfo'], 'purchasing_unit', ''), 's');

    			// 单价
    			$sheet->setCellValueExplicit('N' . $row, $sv['caigou_unitprice'], 'n');

    			// 实际采购量
    			$sheet->setCellValueExplicit('O' . $row, $sv['shiji_caigou_count'], 'n');

    			// 条数
    			$sheet->setCellValueExplicit('P' . $row, $sv['tiaoshu'], 'n');
    			$row++;
    		}
    		$n++;
    	}

    	// Rename worksheet
    	$sheet->setTitle('worksheet');

    	header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    	header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
    	header('Cache-Control: max-age=0');
    	header('Cache-Control: max-age=1');
    	header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
    	header ('Cache-Control: cache, must-revalidate');
    	header ('Pragma: public');

    	$objWriter = \PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
    	$objWriter->save('php://output');
    	exit();
    }

    /**
     * 保存采购备注
     *
     * @author KING
     * @date 2020年7月13日
     *
     */
    public function remark() {
    	$orderId       = $this->request->param('order_id/d', 0);
    	$remark   = $this->request->param('remark/s', '');
    	$upData = [
    		'caigou_remark' => $remark,
    		'update_time' => time(),
    	];
    	$ret = db('order')->where('id', $orderId)->update($upData);
    	$this->addOrderLog($orderId, '', "保存采购备注[{$remark}]");
    	if ($ret) {
    		return $this->Json(1, '保存备注信息成功');
    	} else return $this->Json(0);
    }

    /**
     *
     * 设置采购执行人
     *
     * @author KING
     * @date 2020年7月15日
     *
     */
    public function setCaigouUser() {
    	$orderId  = $this->request->param('order_id/d', 0);
    	$caigouUserId  = $this->request->param('caigou_user_id/d', 0);
    	$upData = [
    		'caigou_user_id' => $caigouUserId,
    		'update_time' => time(),
    	];
    	$ret = db('order')->where('id', $orderId)->update($upData);
    	$systemUserKv = getSystemUserKV(null);
    	$this->addOrderLog($orderId, '', "设置采购执行人为[".arrayGet($systemUserKv, $caigouUserId, '')."]");
    	if ($ret) {
    		return $this->Json(1, '设置采购执行人成功');
    	} else return $this->Json(0);
    }
	/**
     * 到料
     *
     * @date 2020年12月11日
     *
     */
	public function arriveTime(){
		$mid = $this->request->param('mid/d', 0);
		if($mid==0)	return $this->Json(0);
		$result = db('order_material')->where('mid',$mid)->update(['arrive_time'=>time()]);

		$orderId = db('order_material')->where('mid',$mid)->value('order_id', 0);
		// 设置裁床基准物料（客户用量最大的物料）
		$orderMaterialService = new OrderMaterialService();
		$orderMaterialService->setCaichuangStandard($orderId);
		return $this->Json(1);
	}
    /**
     * 打标
     *
     * @author KING
     * @date 2020年7月14日
     *
     */
    public function makeTag() {
    	$mid = $this->request->param('mid/d', 0);
    	$stallsId = $this->request->param('stalls_id/d', 0);
    	$number = $this->request->param('number/d', 0);
    	$isFromStock = $this->request->param('is_from_stock/d', 0);//是否来自库存（0否，1是）
		$isShare = $this->request->param('is_share/d', 0);//是否共用（0否，1是）
    	$isRenew = $this->request->param('is_renew/d', 0);//是否换料
    	$remark = $this->request->param('remark/s', '');
    	$clothNums = $this->request->param('cloth_nums/s', '');

    	$orderService = new OrderService();
    	$orderMaterialService = new OrderMaterialService();
    	$orderMaterialItemService = new OrderMaterialItemService();

    	$orderMaterialInfo = $orderMaterialService->getInfoById($mid);
    	$materialInfo = arrayGet($orderMaterialInfo, 'mInfo', []);
    	$orderInfo = $orderService->getInfoById(arrayGet($orderMaterialInfo, 'order_id', 0));

    	if (empty($orderMaterialInfo) || empty($orderInfo)) {
    		return $this->error('数据异常');
    	}

    	if ($this->request->isAjax()) {

	    	if ($number < 1) {
	    		return $this->error("条数录入错误，仅允许输入正整数");
	    	}

	    	try {
	    		db()->startTrans();

	    		$needShrink = $orderMaterialInfo['need_shrink'];

		    	$oud = [];
		    	$oud['shiji_caigou_count'] = $orderMaterialInfo['shiji_caigou_count'] + $number;
		    	if ($orderMaterialInfo['tiaoshu_detail'] == '' && $number > 0) {
		    		$oud['tiaoshu_detail'] = abs($number);
		    	} else {
		    		$oud['tiaoshu_detail'] = $orderMaterialInfo['tiaoshu_detail'] . ($number < 0 ? $number : '+' . $number);
		    	}
		    	$oud['tiaoshu'] = $oud['shiji_caigou_count'];
		    	$oud['is_make_tag'] = 1;
		    	$oud['is_caigou_start'] = 2;
                $oud['caigou_finish_time'] = time();//采购完成时间
				$oud['is_share'] = $isShare;
		    	$oud['caigou_confirm_status'] = 1;
		    	$oud['caigou_confirm_time'] = time();
		    	$oud['update_time'] = time();


		    	// 处理兴国工厂布料不需要缩水
		    	$excludeIds = trim(config('mp.shrink_task_exclude_factory_id'));
		    	if (in_array($orderInfo['factory_id'], explode(',', $excludeIds))) {
		    		$oud['need_shrink'] = $needShrink = 0;
		    	}

		    	$res = db('order_material')->where('mid', $mid)->update($oud);

		    	// 判断本次是否是换料（即退换料进度表里是否有 换料中状态）
		    	$isRenew = 0;	// 是否换料
		    	$where = [
		    		'order_id' => $orderMaterialInfo['order_id'],
		    		'material_id' => $orderMaterialInfo['material_id'],
		    		'status' => 1,
		    	];
		    	$mrList = db('material_return')->where($where)->select();
		    	if ($mrList) {
		    		$isRenew = 1;
		    		// 将原有换料进行中的记录变更为 审核中
		    		$upData = [
		    			'status' => 2,
		    			'update_time' => time()
		    		];
		    		foreach ($mrList as $k => $v) {
		    			if($v['is_reduce'] == 0 && $v['type'] == 1) {
		    				$upData['is_reduce'] = 1;

		    				// 条数减扣
		    				if ($v['order_material_id'] > 0) {
		    					$omInfo = $orderMaterialService->getInfoById($v['order_material_id'], 'mid,tiaoshu,tiaoshu_detail');
		    					if ($omInfo && $omInfo['tiaoshu'] > 0) {
		    						$omData = [
		    							'tiaoshu' => $omInfo['tiaoshu']-1,
		    							'shiji_caigou_count' => $omInfo['tiaoshu']-1,
		    							'tiaoshu_detail' => $omInfo['tiaoshu_detail'] . '-1',
		    						];
		    						db('order_material')->where('mid', $omInfo['mid'])->update($omData);
		    					}
		    				}
		    			}
		    			db('material_return')->where('id', $v['id'])->update($upData);
		    		}
		    	}

		    	// 记录操作日志
		    	$logData = [
		    		'order_material_id' => $mid,
		    		'factory_id' => $orderMaterialInfo['factory_id'],
		    		'material_id' => arrayGet($materialInfo, 'id', 0),
		    		'material_name' => arrayGet($materialInfo, 'name', ''),
		    		'material_type' => arrayGet($materialInfo, 'type', ''),
		    		'type' => 1,
		    		'order_id' => $orderMaterialInfo['order_id'],
		    		'client_ordernum' => $orderInfo['client_ordernum'],
		    		'color' => arrayGet($materialInfo, 'color', ''),
		    		'tiaoshu' => $number,
		    		'remark' => $remark,
		    		'stalls_id' => $stallsId,
		    		'is_from_stock'=>$isFromStock,
		    		'is_renew'=>$isRenew,
		    		'admin_id'=> ADMIN_ID,
		    		'create_time' => time(),
		    		'update_time' => time(),
		    	];
		    	db('order_material_log')->insertGetId($logData);

		    	// 获取最大的布号
		    	$clothNum = $orderMaterialItemService->getMaxClothNum($orderMaterialInfo['order_id'], $orderMaterialInfo['material_id']);

		    	$clothNumArr = [];
		    	if ($number > 0) {
		    		for ($n=1;$n<=$number;$n++) {
		    			// 插入材料条数记录表
		    			$itemData = [
		    				'order_material_id' => $mid,
		    				'material_id' => $orderMaterialInfo['material_id'],
		    				'order_id' => $orderMaterialInfo['order_id'],
		    				'client_ordernum' => $orderInfo['client_ordernum'],
		    				'stalls_id' => $stallsId,
		    				'cloth_num_full' => $oud['shiji_caigou_count'] . '-' . ($clothNum+$n),
		    				'cloth_num' => $clothNum+$n,
		    				'is_renew' => $isRenew,
							'is_from_stock' => $isFromStock,
							'need_checkcloth'=> $orderMaterialInfo['need_checkcloth'],
		    				'need_shrink'=> $needShrink,
		    				'create_time' => time(),
		    				'update_time' => time(),
		    			];
		    			db('order_material_item')->insertGetId($itemData);
		    			$clothNumArr[] = $itemData['cloth_num'];
		    		}
		    	}
		    	$this->addOrderLog($orderMaterialInfo['order_id'], $orderInfo['client_ordernum'], "物料[".getMaterialName(arrayGet($materialInfo, 'id', 0))."]打标{$number}条");
		    	db()->commit();

		    	$returnData = [
		    		"mid" => $mid,
		    		"shiji_caigou_count" => $oud['shiji_caigou_count'],
		    		"tiaoshu_detail" => $oud['tiaoshu_detail'],
		    		"tiaoshu" => $oud['tiaoshu_detail'],
		    		"url" => url('makeTag', ['mid' => $mid, 'number' => $oud['shiji_caigou_count'], 'is_from_stock' => $isFromStock, 'is_renew' => $isRenew, 'cloth_nums' => implode('-', $clothNumArr)]),
		    	];
				//更新裁剪状态
				$orderMaterialService->updateCaichuangStatus($orderMaterialInfo['order_id'],$mid);
	    		db()->commit();
		    	return $this->Json(1, "保存订单（ID{$orderMaterialInfo['order_id']}，MID{$mid}）条数成功", $returnData);
	    	} catch (\Exception $e) {
	    		db()->rollback();
	    		return $this->Json(0, "打标失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
	    	}
    	}

    	$clothNumMap = db('order_material_item')->where('order_material_id', $mid)->where('cloth_num', 'in', explode('-', $clothNums))->order('cloth_num asc')->column('id,cloth_num_full,cloth_num');

    	foreach ($clothNumMap as $k => &$v) {
    		$msg = "A{$v['id']}-{$v['cloth_num_full']}";
    		$qrCode = new QrCode($msg);
    		$v['qrcode'] = $qrCode->writeDataUri();
    	}

    	$assign = [
    		'materialInfo' => $materialInfo,
    		'orderInfo' => $orderInfo,
    		'factoryKV' => [0=>'']+getFactoryKV(true),
			'materialType' => config('mimo.material_type'),
    		'number' => $number,
    		'isFromStock' => $isFromStock,
    		'isRenew' => $isRenew,
    		'clothNums' => $clothNumMap
    	];
    	$this->view->engine->layout('system@layout_empty');
    	return $this->assign($assign)->fetch();
    }

    /**
     * 批色
     *
     * @author KING
     * @date 2020年7月14日
     *
     */
    public function approvalColor() {
    	$orderId = $this->request->param('order_id/d', 0);
    	$mid = $this->request->param('mid/d', 0);
    	$status = $this->request->param('status/d', 1);

    	$orderService = new OrderService();
    	$orderMaterialService = new OrderMaterialService();
    	$orderMaterialItemService = new OrderMaterialItemService();
    	$orderInfo = $orderService->getInfoById($orderId);

    	if (empty($orderInfo)) return $this->error('订单不存在');

    	if ($mid == 0) {
    		$where = "order_id = {$orderId} and caigou_status = 0";
    		$orderMaterialList = $orderMaterialService->getListByOrderId($orderId);
    		foreach ($orderMaterialList as $k => $v) {
    			if ($v['caigou_status'] != 0) unset($orderMaterialList[$k]);
    		}
    	} else {
    		$orderMaterialList = [['mid' => $mid]];
    	}

    	try {
    		db()->startTrans();
	    	$oud = array(
	    		'update_time' => time(),
	    		'caigou_status' => $status,
	    		'caigou_over_time' => time()
	    	);
	    	$res = db('order_material')->where('mid', 'in', array_column($orderMaterialList, 'mid'))->update($oud);

	    	if ($orderInfo['status'] == 0) $orderData['status'] = 1;
	    	$orderData['update_time'] = time();
	    	$orderData['caigou_user_id'] = ADMIN_ID;

	    	// 检查是否可裁床
//	    	if ($orderMaterialService->checkCanCaiChuang($orderId)) {
//	    		$orderData['caichuang_can_do'] = 1;
//	    		$orderData['caichuang_can_do_time'] = time();
//
//	    		// 设置裁床基准物料（客户用量最大的物料）
//	    		$orderMaterialService->setCaichuangStandard($orderId);
//	    	}

	    	// 检查采购状态是否完成
	    	$isAllOver = 0; // 是否已全部批色
	    	if ($orderMaterialService->checkCaiGouStatus($orderId)) {
	    		$isAllOver = 1;
	    		$orderData['caigou_status'] = 1;
	    		$orderData['caigou_over_time'] = time();
	    	}

	    	db('order')->where('id', $orderId)->update($orderData);
			$orderMaterialService->updateCaichuangStatus($orderId);//更新裁剪状态
			if ($orderMaterialService->checkCaichangCanDoStatus($orderId)) {
	    		// 设置裁床基准物料（客户用量最大的物料）
	    		$orderMaterialService->setCaichuangStandard($orderId);
	    	}
	    	if ($mid == 0) {
	    		$this->addOrderLog($orderId, $orderInfo['client_ordernum'], "全部批色通过");
	    	} else {
	    		$omInfo = $orderMaterialService->getInfoById($mid);
	    		$this->addOrderLog($orderId, $orderInfo['client_ordernum'], "物料[{$omInfo['mInfo']['name']}]批色（mid {$mid}）".($status==1?'通过':'不通过'));
	    	}
	    	db()->commit();
	    	return $this->Json(1, '', ['is_all_over' => $isAllOver, 'order_id' => $orderId]);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '操作失败'.$e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    /**
     * 退料
     *
     * @author KING
     * @date 2020年5月12日
     *
     */
    public function returnClothnum() {
    	$stallsKV = getStallsKV();
    	$mid  = $this->request->param('mid/d', 0);
    	$from  = $this->request->param('from/s', '');	// caichuang从裁床发起退料
    	$materialService = new MaterialService();
    	$orderMaterialService = new OrderMaterialService();
    	$orderMaterialItemService = new OrderMaterialItemService();
    	$omInfo = $orderMaterialService->getInfoById($mid);

    	if ($this->request->isAjax()) {
    		$model  = $this->request->param('model/s', 'get_list');
    		if ($model == 'get_list') {
    			$omList = db('order_material_item')->where(["order_material_id" => $mid, 'flag_del' => 0,])->select();
    			foreach ($omList as $k => $v) {
    				$omList[$k]['mInfo'] = $materialService->getInfoById($v['material_id']);
    				$omList[$k]['stalls_name'] = arrayGet($stallsKV, 'stalls_id', '');
    				$omList[$k]['fabric_width'] = arrayGet($omInfo, 'fabric_width', '');
    				$omList[$k]['weight'] = arrayGet($omInfo, 'weight', '');
    			}
    			$data['data'] = $omList;
    			$data['count'] = count($omList);
    			$data['code'] = 0;
    			$data['msg'] = '';
    			return json($data);
    		}

    		// 整条退料
    		if ($model == 'return_clothnum') {
	    		$id  = $this->request->param('id/d', 0);
	    		$reasonArr  = $this->request->param('reason/a', []);

	    		try {
	    			db()->startTrans();

		    		$info = $orderMaterialItemService->getInfoById($id);

		    		if (!$info) {
		    			return $this->Json(0, "未找到相应数据");
		    		}

		    		if ($info['is_return'] > 0) {
		    			return $this->Json(0, "该布号已退料");
		    		}

		    		// 标记退料
		    		$omiData = [
		    			'is_return' => 1,
		    			'update_time' => time()
		    		];
		    		db('order_material_item')->where('id', $id)->update($omiData);

		    		// 扣除条数
		    		if ($omInfo && $omInfo['tiaoshu'] > 0) {
		    			/* $omData = [
		    				'tiaoshu' => $omInfo['tiaoshu']-1,
		    				'shiji_caigou_count' => $omInfo['tiaoshu']-1,
		    				'tiaoshu_detail' => $omInfo['tiaoshu_detail'] . '-1',
		    			];
		    			db('order_material')->where('mid', $mid)->update($omData); */

		    			// 同步到退料进度表里

		    			$mrData = [
		    				'material_id' => $info['material_id'],
		    				'order_id' => $info['order_id'],
		    				'client_ordernum' => $info['client_ordernum'],
		    				'order_material_id' => $info['order_material_id'],
		    				'order_material_item_id' => $info['id'],
		    				'cloth_num' => $info['cloth_num'],
		    				'type' => 1,
		    				'reason' => implode(',', $reasonArr),
		    				'admin_id' => ADMIN_ID,
		    				'is_reduce' => 0,
		    				'status' => 0,
		    				'create_time' => time(),
		    				'update_time' => time(),
		    			];
		    			$materialReturnId = db('material_return')->insertGetId($mrData);

		    			// 记录退料操作日志
		    			(new MaterialReturnService())->addLog($materialReturnId, 1);
		    		}

		    		// 重新计算唛架信息
		    		if ($from == 'caichuang') {
		    			$orderMaterialService->resetWheatData($mid);
		    		}
					$orderMaterialService->updateCaichuangStatus($info['order_id'],$info['order_material_id']);
		    		$this->addOrderLog($omInfo['order_id'], $omInfo['client_ordernum'], "物料[".getMaterialName($omInfo['material_id'])."]整条退料");
		    		db()->commit();
		    		return $this->Json(1);
	    		} catch (\Exception $e) {
	    			db()->rollback();
	    			return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
	    		}
    		}

    		// 按米退料
    		if ($model == 'return_length') {
    			$id  = $this->request->param('id/d', 0);
    			$returnLength  = $this->request->param('length/d', 0);
    			$reasonArr  = $this->request->param('reason/a', []);

    			try {
    				db()->startTrans();
					$info = $orderMaterialItemService->getInfoById($id);

		    		if (!$info) {
		    			return $this->Json(0, "未找到相应数据");
		    		}

		    		if ($info['is_return'] > 0) {
		    			return $this->Json(0, "该布号已退料");
		    		}
	    			$upData = [
	    				'return_length' => $returnLength,
	    				'update_time' => time(),
	    			];
	    			db('order_material')->where('mid', $mid)->update($upData);

	    			// 同步到退料进度表里
	    			$mrInfo = db('material_return')->where('type', 2)->where('order_material_id', $mid)->field('id')->findOrEmpty();
	    			$mrData = [
	    				'material_id' => $omInfo['material_id'],
	    				'order_id' => $omInfo['order_id'],
	    				'client_ordernum' => $omInfo['client_ordernum'],
	    				'order_material_id' => $mid,
						'order_material_item_id' => $info['id'],
	    				'return_length' => $returnLength,
	    				'type' => 2,
	    				'reason' => implode(',', $reasonArr),
	    				'admin_id' => ADMIN_ID,
	    				'update_time' => time(),
	    			];
	    			if ($mrInfo) {
	    				db('material_return')->where('id', $mrInfo['id'])->update($mrData);
	    			} else {
	    				$mrData['status'] = 0;
	    				$mrData['create_time'] = time();
	    				db('material_return')->insertGetId($mrData);
	    			}

	    			// 重新计算唛架信息
	    			if ($from == 'caichuang') {
	    				$orderMaterialService->resetWheatData($mid);
	    			}
					$orderMaterialService->updateCaichuangStatus($info['order_id'],$info['order_material_id']);
	    			$this->addOrderLog($omInfo['order_id'], $omInfo['client_ordernum'], "物料[".getMaterialName($omInfo['material_id'])."]按米退料{$returnLength}米");
	    			db()->commit();
	    			return $this->Json(1);
    			} catch (\Exception $e) {
    				db()->rollback();
    				return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    			}
    		}
    	}

    	$assign = [
    		'mid' => $mid,
    		'from' => $from,
    	];
    	return $this->assign($assign)->fetch();
    }
	/**
     * 删除布条
     *
     * @author KING
     * @date 2020年5月12日
     *
     */
    public function delClothnum() {
    	$stallsKV = getStallsKV();
    	$mid  = $this->request->param('mid/d', 0);
		$id = $this->request->param('id/d', 0);

    	$materialService = new MaterialService();
    	$orderMaterialService = new OrderMaterialService();
    	$orderMaterialItemService = new OrderMaterialItemService();
    	$omInfo = $orderMaterialService->getInfoById($mid);
    	$omiInfo = $orderMaterialItemService->getInfoById($id);
    	if (empty($omInfo) || empty($omiInfo)) return $this->error('请求异常');
		if (db('checkcloth_shrink')->where('order_material_item_id', $id)->find()) {
			return $this->error('已存在验布或缩水记录，不允许删除');
		}

		try {
			db()->startTrans();

			db('order_material_item')->where("id", $id)->delete();

			// 记录操作日志
			$logData = [
				'order_material_id' => $mid,
				'factory_id' => $omInfo['factory_id'],
				'material_id' => arrayGet($omInfo, 'material_id', 0),
				'material_name' => arrayGet($omInfo['mInfo'], 'name', ''),
				'material_type' => arrayGet($omInfo['mInfo'], 'type', ''),
				'type' => 2,
				'order_id' => $omInfo['order_id'],
				'client_ordernum' => $omInfo['client_ordernum'],
				'color' => arrayGet($omInfo['mInfo'], 'color', ''),
				'tiaoshu' => 1,
				'remark' => '删除布条' . $omiInfo['cloth_num_full'],
				'stalls_id' => 0,
				'is_from_stock'=>0,
				'is_renew'=>0,
				'admin_id'=>ADMIN_ID,
				'create_time' => time(),
				'update_time' => time(),
			];
			db('order_material_log')->insertGetId($logData);

			$omUpdInfo=[
				'tiaoshu' => $omInfo['tiaoshu']-1,
				'tiaoshu_detail' => $omInfo['tiaoshu_detail'].'-1',
				'shiji_caigou_count' => $omInfo['shiji_caigou_count']-1,
				'update_time' => time(),
			];
			db('order_material')->where("mid", $mid)->update($omUpdInfo);
			$tiaoshu=db('order_material')->where("mid", $mid)->value('tiaoshu');
			if($tiaoshu==0){
				db('order_material')->where("mid", $mid)->update(['is_make_tag'=>0]);
			}

			// 记录操作日志
			$this->addOrderLog($omInfo['order_id'], $omInfo['client_ordernum'], "删除物料[{$omInfo['mInfo']['name']}]布条" . $omiInfo['cloth_num_full']);

			db()->commit();

			return $this->Json(1,"操作成功");
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
    }

	/**
	 * 采购面板
	 *
	 * @author KING
	 * @date 2020年7月1日
	 *
	 * @return string
	 */
    public function panel()
    {
        if ($this->request->isPost()) {
        	$createDate  = $this->request->param('date/s', '');
        	if(!isDateTime($createDate, 'Y-m-d')) $createDate = '';

        	$where = [];
        	$where[] = ['caigou_status', '=', 0];
        	$where[] = ['status', 'in', [0, 1]];
            //订单加一级
            order_level($where,'');
        	if ($createDate != '') {
        		$where[] = ['create_time', 'between', [strtotime($createDate.' 00:00:00'), strtotime($createDate.' 23:59:59')]];
        	}
        	$list = db('order')->where($where)->order('shipment_time asc')->select();
        	$skus = array_column($list, 'sku');
        	$skuKV = db('sku')->where('sku', 'in', $skus)->column('ori_pic', 'sku');
        	$factoryOutgoKV = getFactoryOutgoKV(null);

        	$key = 'caigou';
        	$result = [
        		$key . '_orders' => count($list),
        		$key . '_items' => array_sum(array_column($list, 'quantity')),
        	];
        	$memoService = new MemoService();
        	foreach ($list as $v) {
        		// 判断采购是否异常
        		$exception = $memoService->getPurchasingException($v['id']);
        		$result[$key][] = [
        			'exception' => $exception,
        			'client_ordernum' => $v['client_ordernum'],
        			'sku' => $v['sku'],
        			'quantity' => $v['quantity'],
        			'shipment_time' => date("Y-m-d", $v['shipment_time']),
        			'factory_outgo_name' => arrayGet($factoryOutgoKV, $v['factory_outgo_id'], ''),
        			'pic' => arrayGet($skuKV, $v['sku'], ''),
        			'tags' => getOrderTag($v),
        		];
        	}

        	return $this->Json(1, '', $result);
        }

        return $this->fetch();
    }

    /**
     * 采购成本
     *
     * @author KING
     * @date 2020年7月30日
     *
     */
    public function cost() {
    	$factoryKV = getFactoryKV(true);
    	$systemUserKV = getSystemUserKV(null);
		$stallsKV = getStallsKV();
    	if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$factoryId  = $this->request->param('factory_id/d', 0);
    		$clientOrdernum    = $this->request->param('client_ordernum/s');
    		$sku    	= $this->request->param('sku/s', '');
    		$orderStatus    	= $this->request->param('order_status/d', 0);
			$urgeOrder    	= $this->request->param('urge_order/d', 2);
    		$createDateRange    = $this->request->param('create_date_range/s');
			$caigouCostOverTime    = $this->request->param('caigou_cost_over_time/s');
			$isShare  = $this->request->param('is_share/d', 0);
			$export     = $this->request->param('export/d', 0);

            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    $ext_id != '' && $where[] = ['ext_id', '=', $ext_id];
                    break;
            }
			if ($orderStatus == 99) $where[] = ['status', '=', 99];
			elseif ($clientOrdernum == '') $where[] = ['status', 'in', [0, 1, 2]];

    		$where[] = ['o_type', 'in', ['FOB', 'CMT2']];
			if ($export) {
    			set_time_limit(0);
    			ini_set('memory_limit', '1024M');
    			$page = 1;
    			$limit = 99999;
    		}
    		if ($factoryId > 0) {
    			$where[] = ['factory_id', '=', $factoryId];
    		}
			if ($isShare!=2) {
				$subQuerys = db('order_material')->where('is_share',$isShare)->distinct(true)->field('order_id')->buildSql();
				$where[] = ['id', 'exp', Db::raw("in({$subQuerys})")];
    		}
    		if ($clientOrdernum != '') {
    			$where[] = ['client_ordernum', 'in', $clientOrdernum];
    		}
    		if ($sku != '') {
    			$where[] = ['sku', 'like', "%".$sku."%"];
    		}
			if ($caigouCostOverTime != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $caigouCostOverTime));
    			$whereTime[] = ['caigou_cost_over_time', 'between', [$startTime, $endTime+86399]];
				$subQuery = db('order_material')->where($whereTime)->distinct(true)->field('order_id')->buildSql();
				$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
    		}
    		if ($orderStatus != '') {
    			switch ($orderStatus){
    				case 1:
    					$where[] = ['caigou_status', '=', 0];
    					break;
    				case 2:
    					$where[] = ['caigou_status', '=', 1];
    					$where[] = ['caichuang_status', '=', 0];
    					break;
    				case 3:
    					$where[] = ['caichuang_status', '=', 1];
    					$where[] = ['chejian_status', '=', 0];
    					break;
    				case 4:
    					$where[] = ['chejian_status', '=', 1];
    					$where[] = ['tail_status', '=', 0];
    					break;
    				case 5:
    					$where[] = ['tail_status', '=', 1];
    					$where[] = ['status', '=', 0];
    					break;
    				case 6:
    					$where[] = ['status', '=', 2];
    					break;
    			}
    		}
			if ($urgeOrder != 2) {
    			switch ($urgeOrder){
    				case 0:
						$subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("om.caigou_cost_status=0 and om.is_make_tag=1 and m.type !='accessories'")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("not in({$subQuery})")];
    					break;
    				case 1:
    					$subQuery = db('order_material om')->join('material m', "om.material_id=m.id", 'left')->where("om.caigou_cost_status=0 and om.is_make_tag=1 and m.type !='accessories'")->distinct(true)->field('om.order_id')->buildSql();
    					$where[] = ['id', 'exp', Db::raw("in({$subQuery})")];
    					break;
    			}
    		}
    		if ($createDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
    			$where[] = ['create_time', 'between', [$startTime, $endTime+86399]];
    		}

    		$order = "FIELD(status,2,99) ASC,caigou_status ASC, caigou_over_time DESC, id DESC";
    		$list = db('order')->where($where)->page($page)->limit($limit)->orderRaw($order)->select();

    		$skuService = new SkuService();
			$stallFeedService = new StallFeedService();
    		$orderSizeService = new OrderSizeService();
    		$orderMaterialService = new OrderMaterialService();
			$orderMaterialItemService=new OrderMaterialItemService();
    		foreach ($list as $k => $v) {
    			$osList = $orderSizeService->getListByOrderId($v['id']);
    			$list[$k]['osList'] = $osList;
    			$list[$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
    			$list[$k]['o_type_text'] = arrayGet(config('mimo.order_otype'), $v['o_type'], '');
    			$list[$k]['sInfo'] = $skuService->getInfoBySku($v['sku']);
    			$list[$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
    			$list[$k]['caichuang_user_name'] = arrayGet($systemUserKV, $v['caichuang_user_id'], '');
    			$list[$k]['caigou_user_name'] = arrayGet($systemUserKV, $v['caigou_user_id'], '');
    			$list[$k]['omList'] =$omList= $orderMaterialService->getListByOrderId($v['id']);
    			$list[$k]['delete_text'] = $v['status'] == 99 ? '已废除' : '';
				if ($export) {
					if(!$list[$k]['omList']) unset($v);
				}
				$list[$k]['urgeOrder']=0;
				foreach ($list[$k]['omList'] as $kom => $vom) {
					if($vom['caigou_cost_status']!=1 &&$vom['is_make_tag']==1 && $vom['mInfo']['type']!="accessories") $list[$k]['urgeOrder']=1;
					$list[$k]['omList'][$kom]['stall_name']='';
					$list[$k]['omList'][$kom]['stall_id']=0;
					$omiList=$orderMaterialItemService->getListByOrderMaterialId($vom['mid'],"stalls_id",$isReturn=null);
					if($omiList){
						$list[$k]['omList'][$kom]['stall_name']=arrayGet(getStallsKV(),$omiList[0]['stalls_id'],'');
						$list[$k]['omList'][$kom]['stall_id']=$omiList[0]['stalls_id'];
					}
				}

    		}
//                $data=[
//                    'orderFrom' => [0 => ''] + config('mimo.order_from'),
//                    'count'=>db('order')->where($where)->count('id'),
//                    'data'=>$list,
//                    'code'=>0,
//                    'msg'=>''
//                ];
    		$data['count'] = db('order')->where($where)->count('id');
    		$data['data'] = $list;
			if ($export) {
    			$this->_exportCostXls('采购成本-' .date('YmdHis'), $list);
    			exit;
    		}
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}

    	$assign = [
    		'factoryKV' => ['0' => '请选择'] + $factoryKV,
			'stallsKV' => ['0' => '请选择'] + $stallsKV,
    	];
    	return $this->assign($assign)->fetch();
    }
	/**
		 * 采购成本导出
		 *
		 * @author KING
		 * @date 2020年7月30日
		 *
     */
	private function _exportCostXls($fileName, $data) {
    	$head = ['下单时间','订单编号','SKU','材料名称','供应商','型号','色号','颜色','采购量','单位','单价','开单采购总数','采购条数','金额','足米','签单'];

    	$phpExcel = getExcelObj();
    	$sheet = $phpExcel->setActiveSheetIndex(0);
    	// 表头处理
    	foreach ($head as $k => $v) {
    		$cellKey = getExcelLetter($k);
    		$sheet->getColumnDimension($cellKey)->setWidth(20);
    		$sheet->setCellValue($cellKey . "1", $v);
    		$sheet->getRowDimension(1)->setRowHeight(30);
    		$sheet->getStyle($cellKey . "1")->getFont()->setBold(true);
    		$sheet->getStyle($cellKey . "1")->getAlignment()->setVertical('center');
    		$sheet->getStyle($cellKey . "1")->getFont()->getColor()->setARGB("FF0000FF");
    	}

    	$skuService = new SkuService();
    	require_once env('root_path').'plugins/excel/phpexcel/Classes/PHPExcel/Worksheet/Drawing.php';

    	$row = 2; // 当前行
    	$n = 0;
    	foreach ($data as $k => $v) {
    		if (count($v['omList']) > 1) {
    			$endCol = $row + count($v['omList']) - 1;
    			$sheet->mergeCells('A' . $row . ':A' . $endCol);
    			$sheet->mergeCells('B' . $row . ':B' . $endCol);
				$sheet->mergeCells('C' . $row . ':C' . $endCol);
    		}

    		$sheet->getStyle('A' . $row)->getAlignment()->setVertical('center');
    		$sheet->getStyle('B' . $row)->getAlignment()->setVertical('center');
			$sheet->getStyle('C' . $row)->getAlignment()->setVertical('center');

			$sheet->setCellValueExplicit('A' . $row, $v['create_time'] == 0 ? '':date('Y-m-d H:i:s', $v['create_time']), 's');
    		$sheet->setCellValueExplicit('B' . $row, $v['client_ordernum'], 'n');
    		$sheet->setCellValueExplicit('C' . $row, $v['sku'], 's');

    		foreach ($v['omList'] as $sk => $sv) {
    			//$sheet->getRowDimension($row)->setRowHeight(22);

    			$sheet->setCellValueExplicit('D' . $row, arrayGet($sv['mInfo'], 'name', ''), 's');
    			$sheet->setCellValueExplicit('E' . $row, arrayGet($sv['mInfo'], 'supplier', ''), 's');
    			$sheet->setCellValueExplicit('F' . $row, arrayGet($sv['mInfo'], 'model', ''), 's');

    			// 色号
    			$sheet->setCellValueExplicit('G' . $row, arrayGet($sv['mInfo'], 'colornum', ''), 'n');

    			// 颜色
    			$sheet->setCellValueExplicit('H' . $row, arrayGet($sv['mInfo'], 'color', ''), 's');

    			// 采购量
    			$sheet->setCellValueExplicit('I' . $row, $sv['material_dosage'], 'n');

				// 单位
    			$sheet->setCellValueExplicit('J' . $row, arrayGet($sv['mInfo'], 'purchasing_unit', ''), 's');
    			// 单价
    			$sheet->setCellValueExplicit('K' . $row, $sv['caigou_unitprice'], 'n');

    			// 开单采购总数
    			$sheet->setCellValueExplicit('L' . $row, $sv['billing_caigou_count'], 'n');

    			// 条数
    			$sheet->setCellValueExplicit('M' . $row, $sv['tiaoshu'], 'n');
				// 金额
    			$sheet->setCellValueExplicit('N' . $row, $sv['caigou_subtotal_money'], 'n');
				// 足米
    			$sheet->setCellValueExplicit('O' . $row, $sv['caigou_is_enough'], 's');
				// 签单
    			$sheet->setCellValueExplicit('P' . $row, $sv['caigou_is_sign'], 's');
    			$row++;
    		}
    		$n++;
    	}

    	// Rename worksheet
    	$sheet->setTitle('worksheet');

    	header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    	header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
    	header('Cache-Control: max-age=0');
    	header('Cache-Control: max-age=1');
    	header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
    	header ('Cache-Control: cache, must-revalidate');
    	header ('Pragma: public');

    	$objWriter = \PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
    	$objWriter->save('php://output');
    	exit();
    }
    /**
     * 保存采购成本备注
     *
     * @author KING
     * @date 2020年7月13日
     *
     */
    public function costRemark() {
    	$orderId       = $this->request->param('order_id/d', 0);
    	$remark   = $this->request->param('remark/s', '');
    	$upData = [
    		'caigou_cost_remark' => $remark,
    		'update_time' => time(),
    	];
    	$ret = db('order')->where('id', $orderId)->update($upData);
    	$this->addOrderLog($orderId, '', "保存采购成本备注[{$remark}]");
    	if ($ret) {
    		return $this->Json(1, '保存采购成本备注成功');
    	} else return $this->Json(0);
    }

    /**
     * 保存采购核价备注
     *
     * @author KING
     * @date 2020年7月13日
     *
     */
    public function caigouPricing() {
    	$orderId       = $this->request->param('order_id/d', 0);
    	$remark   = $this->request->param('remark/s', '');
    	$upData = [
    		'caigou_pricing' => $remark,
    		'update_time' => time(),
    	];
    	$ret = db('order')->where('id', $orderId)->update($upData);
    	$this->addOrderLog($orderId, '', "保存采购核价备注[{$remark}]");
    	if ($ret) {
    		return $this->Json(1, '保存采购核价备注成功');
    	} else return $this->Json(0);
    }

    /**
     * 采购成本确认
     *
     * @author KING
     * @date 2020年7月31日
     *
     * @throws \Exception
     */
    public function costConfirm() {
    	$mid  = $this->request->param('mid/d', 0);
    	$caigouUnitprice   = $this->request->param('caigou_unitprice/f', 0);
    	$billingCaigouCount   = $this->request->param('billing_caigou_count/f', 0);
    	$billingCaigouCountOri   = $this->request->param('billing_caigou_count_ori/f', 0);
    	$caigouSubtotalMoney   = $this->request->param('caigou_subtotal_money/f', 0);
    	$trueFabricWidth   = $this->request->param('true_fabric_width/f', 0);
    	$trueWeight   = $this->request->param('true_weight/f', 0);
    	$caigouIsEnough   = $this->request->param('caigou_is_enough/d', 0);
    	$caigouIsSign   = $this->request->param('caigou_is_sign/d', 0);
		$billingCaigouKgcount   = $this->request->param('billing_caigou_kgcount/f', 0);
    	$billingCaigouKgprice   = $this->request->param('billing_caigou_kgprice/f', 0);
		$stallOrderTime   = $this->request->param('stall_order_time/s', '');
    	$stallOrder   = $this->request->param('stall_order/s', '');
		$stallId   = $this->request->param('stall_id/d', 0);

    	$orderService = new OrderService();
    	$orderMaterialService = new OrderMaterialService();
		$orderMaterialItemService = new OrderMaterialItemService();
    	try {
    		db()->startTrans();

	    	// 记录原始开单采购数
	    	$omInfo = $orderMaterialService->getInfoById($mid);
	    	if (empty($omInfo)){
	    		throw new \Exception('数据异常');
	    	}
			if($stallId){
				$omiList=$orderMaterialItemService->getListByOrderMaterialId($mid,"id,stalls_id");
				if($omiList) db('order_material_item')->where('id',$omiList[0]['id'])->update(['stalls_id'=>$stallId]);
			}

	    	$oud = [
	    		'update_time' => time(),
	    		'billing_caigou_count' => $billingCaigouCount,
	    		'billing_caigou_count_ori' => $billingCaigouCountOri,
				'billing_caigou_kgcount' => $billingCaigouKgcount,
				'billing_caigou_kgprice' => $billingCaigouKgprice,
	    		'caigou_cost_status' => 2,
	    		//'caigou_cost_over_time' => time(),
	    		'caigou_unitprice' => $caigouUnitprice,
	    		'caigou_subtotal_money' => round($caigouSubtotalMoney, 2),
	    		'caigou_is_enough' => $caigouIsEnough,
	    		'caigou_is_sign' => $caigouIsSign,
	    		'true_fabric_width' => $trueFabricWidth,
	    		'true_weight' => $trueWeight,
				'stall_order'=>$stallOrder,
				'stall_order_time'=>strtotime($stallOrderTime)?strtotime($stallOrderTime):0,
	    	];
	    	$orderId = $omInfo['order_id'];
	    	$res = db('order_material')->where('mid', $mid)->update($oud);

	    	// 同步修改初单信息start
	    	$sfData = [
	    		'update_time' => time(),
	    		'billing_caigou_count_feed' => $billingCaigouCountOri,
	    		'billing_caigou_kgcount' => $billingCaigouKgcount,
	    		'billing_caigou_kgprice' => $billingCaigouKgprice,
	    		'caigou_unitprice' => $caigouUnitprice,
	    		'settle_unitprice' => min([$caigouUnitprice, $omInfo['customer_price']]),
	    	];
	    	$sfData['settle_amount'] = round($sfData['settle_unitprice'] * abs(floatval($billingCaigouCountOri)), 2);
	    	db('stall_feed')->where('order_material_id', $mid)->where('original', 1)->update($sfData);
	    	// 同步修改初单信息end

			//检验物料损耗
			$exception=0;$msg="";
			$dif1 = $orderMaterialService->checkClothLossStatus($omInfo['mid']);
			if ($dif1) {
				$exception=1;//验布损耗大于0.06 true=1 ,false=0
				$msg=$msg."该单物料亏损严重，差异".$dif1."米</br>";
			}
			$dif2 = $orderMaterialService->checkShrinkLossStatus1($omInfo['mid']);
			if ($dif2) {
				$exception=1;//缩水1损耗大于0.02 true=1 ,false=0
				$msg=$msg."该单物料亏损严重，差异".$dif2."公斤</br>";
			}
			$dif3 = $orderMaterialService->checkShrinkLossStatus2($omInfo['mid']);
			if ($dif3) {
				$exception=1;
				$msg=$msg."该单物料亏损严重，差异".$dif3."克重</br>";
			}
			$dif4 = $orderMaterialService->checkCaichuangLossStatus1($omInfo['mid']);
			if ($dif4) {
				$exception=1;
				$msg=$msg."该单物料亏损严重，差异".$dif4."件</br>";
			}
			$dif5 = $orderMaterialService->checkCaichuangLossStatus2($omInfo['mid']);
			if ($dif5) {
				$exception=1;
				$msg=$msg."该单物料亏损严重，差异".$dif5."米";
			}
			$this->addOrderLog($orderId, $omInfo['client_ordernum'], "物料[{$omInfo['mInfo']['name']}]采购成本确认");

	    	db()->commit();
	    	return $this->Json(1,'',['exception'=>$exception,'msg'=>$msg]);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }
	/**
     * 采购成本更正
     *
     * @author KING
     * @date 2020年7月31日
     *
     * @throws \Exception
     */
    public function costConfirm1() {
    	$mid  = $this->request->param('mid/d', 0);
    	$caigouUnitprice   = $this->request->param('caigou_unitprice/f', 0);
    	$billingCaigouCount   = $this->request->param('billing_caigou_count/f', 0);
    	$billingCaigouCountOri   = $this->request->param('billing_caigou_count_ori/f', 0);
    	$caigouSubtotalMoney   = $this->request->param('caigou_subtotal_money/f', 0);
    	$trueFabricWidth   = $this->request->param('true_fabric_width/f', 0);
    	$trueWeight   = $this->request->param('true_weight/f', 0);
    	$caigouIsEnough   = $this->request->param('caigou_is_enough/d', 0);
    	$caigouIsSign   = $this->request->param('caigou_is_sign/d', 0);
		$billingCaigouKgcount   = $this->request->param('billing_caigou_kgcount/f', 0);
    	$billingCaigouKgprice   = $this->request->param('billing_caigou_kgprice/f', 0);
		$stallOrderTime   = $this->request->param('stall_order_time/s', '');
    	$stallOrder   = $this->request->param('stall_order/s', '');
		$stallId   = $this->request->param('stall_id/d', 0);

    	$orderService = new OrderService();
    	$orderMaterialService = new OrderMaterialService();
		$orderMaterialItemService = new OrderMaterialItemService();
    	try {
    		db()->startTrans();

	    	// 记录原始开单采购数
	    	$omInfo = $orderMaterialService->getInfoById($mid);
	    	if (empty($omInfo)){
	    		throw new \Exception('数据异常');
	    	}
			if($stallId){
				$omiList=$orderMaterialItemService->getListByOrderMaterialId($mid,"id,stalls_id");
				if($omiList) db('order_material_item')->where('id',$omiList[0]['id'])->update(['stalls_id'=>$stallId]);
			}

	    	$oud = [
	    		'update_time' => time(),
	    		'billing_caigou_count' => $billingCaigouCount,
	    		'billing_caigou_count_ori' => $billingCaigouCountOri,
				'billing_caigou_kgcount' => $billingCaigouKgcount,
				'billing_caigou_kgprice' => $billingCaigouKgprice,
	    		//'caigou_cost_status' => 2,
	    		//'caigou_cost_over_time' => time(),
	    		'caigou_unitprice' => $caigouUnitprice,
	    		'caigou_subtotal_money' => round($caigouSubtotalMoney, 2),
	    		'caigou_is_enough' => $caigouIsEnough,
	    		'caigou_is_sign' => $caigouIsSign,
	    		'true_fabric_width' => $trueFabricWidth,
	    		'true_weight' => $trueWeight,
				'stall_order'=>$stallOrder,
				'stall_order_time'=>strtotime($stallOrderTime)?strtotime($stallOrderTime):0,
	    	];
	    	$orderId = $omInfo['order_id'];

	    	$res = db('order_material')->where('mid', $mid)->update($oud);

			//同步更新对账表
			$nomInfo = $orderMaterialService->getInfoById($mid);
			$sfData=[
				'billing_caigou_count_feed'=>$nomInfo['billing_caigou_count_ori'],
				//'order_material_id'=>$mid,
				'stall_id'=>$stallId,
				'caigou_unitprice'=>$nomInfo['caigou_unitprice'],
				'billing_caigou_kgcount'=>$nomInfo['billing_caigou_kgcount'],
				'billing_caigou_kgprice'=>$nomInfo['billing_caigou_kgprice'],
				'order_id'=>$nomInfo['order_id'],
				'client_ordernum'=>$nomInfo['client_ordernum'],
				'material_id'=>$nomInfo['material_id'],
				'stall_order_time'=>$nomInfo['stall_order_time'],
				'stall_order'=>$nomInfo['stall_order'],
				'admin_id'=>ADMIN_ID,
				'settle_unitprice' => min([$nomInfo['caigou_unitprice'], $nomInfo['customer_price']]),
				'update_time' => time(),
				'create_time' => time(),
			];
			$sfData['settle_amount'] = round($sfData['settle_unitprice'] * abs(floatval($nomInfo['billing_caigou_count_ori'])), 2);
			db('stall_feed')->where("order_material_id=".$mid." and original=1")->update($sfData);
			$exception=0;$msg="";
			$dif1 = $orderMaterialService->checkClothLossStatus($omInfo['mid']);
			if ($dif1) {
				$exception=1;//验布损耗大于0.06 true=1 ,false=0
				$msg=$msg."该单物料亏损严重，差异".$dif1."米</br>";
			}
			$dif2 = $orderMaterialService->checkShrinkLossStatus1($omInfo['mid']);
			if ($dif2) {
				$exception=1;//缩水1损耗大于0.02 true=1 ,false=0
				$msg=$msg."该单物料亏损严重，差异".$dif2."公斤</br>";
			}
			$dif3 = $orderMaterialService->checkShrinkLossStatus2($omInfo['mid']);
			if ($dif3) {
				$exception=1;
				$msg=$msg."该单物料亏损严重，差异".$dif3."克重</br>";
			}
			$dif4 = $orderMaterialService->checkCaichuangLossStatus1($omInfo['mid']);
			if ($dif4) {
				$exception=1;
				$msg=$msg."该单物料亏损严重，差异".$dif4."件</br>";
			}
			$dif5 = $orderMaterialService->checkCaichuangLossStatus2($omInfo['mid']);
			if ($dif5) {
				$exception=1;
				$msg=$msg."该单物料亏损严重，差异".$dif5."米";
			}

			$this->addOrderLog($orderId, $omInfo['client_ordernum'], "物料[{$nomInfo['mInfo']['name']}]采购成本确认更正");

	    	db()->commit();
	    	return $this->Json(1,'',['exception'=>$exception,'msg'=>$msg]);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    /**
     * 异步计算小计金额
     *
     * @author King
     * @date 2021年7月21日
     *
     */
    public function getCaigouSubtotalMoney() {
    	$mid  = $this->request->param('mid/d', 0);
    	$caigouUnitprice   = $this->request->param('caigou_unitprice/f', 0);
    	$billingCaigouCountOri   = $this->request->param('billing_caigou_count_ori/f', 0);

    	$orderMaterialService = new OrderMaterialService();
    	$stallFeedService=new StallFeedService();

    	$omInfo = $orderMaterialService->getInfoById($mid);
    	$sfList = $stallFeedService->getListByMid($mid);

    	$caigouSubtotalMoney = round($caigouUnitprice * $billingCaigouCountOri, 2);
    	foreach ($sfList as $key => $value) {
    		if ($value['original'] == 1) continue; // 初单的金额无需再次计入
    		$billingCaigouCountFeed = floatval($value['billing_caigou_count_feed']);
    		$caigouSubtotalMoney = ($value['caigou_unitprice']*$billingCaigouCountFeed) + $caigouSubtotalMoney;
    	}

    	$result = [
    		'caigouSubtotalMoney' => round($caigouSubtotalMoney, 2),
    		'billingCaigouCount' => $omInfo['billing_caigou_count']-$omInfo['billing_caigou_count_ori']+$billingCaigouCountOri,
    	];
    	return $this->Json(1, '操作成功', $result);

    }

	/**
     * 采购成本审核
     *
     * @author KING
     * @date 2020年7月31日
     *
     * @throws \Exception
     */
	public function costCheck(){
		$mid  = $this->request->param('mid/d', 0);
		$stall_id  = $this->request->param('stall_id/d', 0);
		$orderService = new OrderService();
		$orderMaterialService = new OrderMaterialService();
		$orderMaterialItemService=new OrderMaterialItemService();
		try {
    		db()->startTrans();

	    	// 记录原始开单采购数
	    	$omInfo = $orderMaterialService->getInfoById($mid);
	    	if (empty($omInfo)){
	    		throw new \Exception('数据异常');
	    	}

	    	$oud = [
	    		'update_time' => time(),
				'caigou_cost_status' => 1,
	    		'caigou_cost_over_time' => time(),
	    	];

	    	$orderId = $omInfo['order_id'];

	    	$res = db('order_material')->where('mid', $mid)->update($oud);
	    	$orderInfo = $orderService->getInfoById($orderId);
	    	if ($orderInfo['status'] == 0) $orderData['status'] = 1;
	    	$orderData['update_time'] = time();

	    	// 采购成本是否全部确认
	    	if ($orderInfo['o_type'] == 'FOB') {
	    		$orderMaterialInfo = db('order_material')->where("order_id = {$orderId} and caigou_cost_status = 0")->field('mid')->findOrEmpty();
	    	} elseif($orderInfo['o_type'] == 'CMT2') {
	    		$orderMaterialInfo = db('order_material om')->join('material m', 'om.material_id = m.id')->where('m.type', 'accessories')->where(['om.order_id' => $orderId, 'om.caigou_cost_status' => 0])->field('om.mid')->findOrEmpty();
	    	} else $orderMaterialInfo = false;

	    	if (!$orderMaterialInfo) {
	    		$orderData['caigou_cost_status'] = 1;
	    	}

	    	// 采购合计金额
	    	$orderData['caigou_total_money'] = $orderMaterialService->getAllCaigouSubtotalMoney($orderId);
	    	db('order')->where('id', $orderId)->update($orderData);
			$nomInfo = $orderMaterialService->getInfoById($mid);
			$sfData=[
				'billing_caigou_count_feed'=>$nomInfo['billing_caigou_count_ori'],
				'order_material_id'=>$mid,
				'stall_id'=>$stall_id,
				'caigou_unitprice'=>$nomInfo['caigou_unitprice'],
				'billing_caigou_kgcount'=>$nomInfo['billing_caigou_kgcount'],
				'billing_caigou_kgprice'=>$nomInfo['billing_caigou_kgprice'],
				'order_id'=>$nomInfo['order_id'],
				'client_ordernum'=>$nomInfo['client_ordernum'],
				'material_id'=>$nomInfo['material_id'],
				'status'=>1,
				'stall_order_time'=>$nomInfo['stall_order_time'],
				'stall_order'=>$nomInfo['stall_order'],
				'settle_unitprice' => min([$nomInfo['caigou_unitprice'], $nomInfo['customer_price']]),
				'original'=>1,
				'admin_id'=>ADMIN_ID,
				'update_time' => time(),
				'create_time' => time(),
			];
			$sfData['settle_amount'] = round($sfData['settle_unitprice'] * abs(floatval($sfData['billing_caigou_count_feed'])), 2);
			db('stall_feed')->insert($sfData);

	    	$this->addOrderLog($orderId, $omInfo['client_ordernum'], "物料[{$omInfo['mInfo']['name']}]采购成本通过审核");

	    	db()->commit();
	    	return $this->Json(1);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
	}


    /**
     * 采购成本补料
     *
     * @author KING
     * @date 2020年7月31日
     *
     */
    public function costFeed() {
    	$mid  = $this->request->param('mid/d', 0);
    	$number = $this->request->post('number/f', 0); // 补料
		$billingCaigouKgcount=$this->request->post('billing_caigou_kgcount/f', 0); // 开单公斤数
    	$orderService = new OrderService();
    	$orderMaterialService = new OrderMaterialService();
		$orderMaterialItemService=new OrderMaterialItemService();
		$stallFeedService=new StallFeedService();
    	try {
    		db()->startTrans();

    		$omInfo = $orderMaterialService->getInfoById($mid);
    		if (empty($omInfo)){
    			throw new \Exception('数据异常');
    		}

	    	$orderId = $omInfo['order_id'];

	    	$billingCaigouCount = $omInfo['billing_caigou_count'] + $number;

			//新增补退明细表记录
			$omiList=$orderMaterialItemService->getListByOrderMaterialId($mid,"stalls_id");
			if($omiList) $sfData['stall_id']=$omiList[0]['stalls_id'];
			$sfData=[
				'billing_caigou_count_feed'=>$number >= 0 ? '+'.abs($number) : $number,
				'billing_caigou_kgcount' => $billingCaigouKgcount,
				'order_material_id'=>$mid,
				'order_id'=>$omInfo['order_id'],
				'client_ordernum'=>$omInfo['client_ordernum'],
				'material_id'=>$omInfo['material_id'],
				'admin_id'=>ADMIN_ID,
				'update_time' => time(),
				'create_time' => time(),
			];
			db('stall_feed')->insert($sfData);
			//同时更新order_material和order
			$sfList=$stallFeedService->getListByMid($omInfo['mid']);
			$caigouSubtotalMoney = $omInfo['caigou_unitprice'] * $omInfo['billing_caigou_count_ori'];
			foreach ($sfList as $key => $value) {
				$caigouSubtotalMoney = $caigouSubtotalMoney+($value['caigou_unitprice']*$value['billing_caigou_count_feed']);
			}
			$oud = array(
	    		'update_time' => time(),
	    		'billing_caigou_count_feed' => $omInfo['billing_caigou_count_feed'] . ($number >= 0 ? '+'.abs($number) : $number),
	    		'billing_caigou_count' => $billingCaigouCount,
	    		'caigou_subtotal_money' => round($caigouSubtotalMoney, 2),
	    	);
	    	$res = db('order_material')->where('mid', $mid)->update($oud);
	    	$orderInfo = $orderService->getInfoById($orderId);
	    	if ($orderInfo['status'] == 0) $orderData['status'] = 1;
	    	$orderData['update_time'] = time();

	    	// 采购合计金额stallFeedDetail
	    	$orderData['caigou_total_money'] = $orderMaterialService->getAllCaigouSubtotalMoney($orderId);
	    	db('order')->where('id', $orderId)->update($orderData, "id = " . $orderId);
    		$this->addOrderLog($orderId, $orderInfo['client_ordernum'], "物料[{$omInfo['mInfo']['name']}]补料".$number);

    		db()->commit();
    		$res = [
    			'order_id' => $orderId,
    			'billing_caigou_count' => $billingCaigouCount,
    			'caigou_subtotal_money' => $caigouSubtotalMoney,
    			'caigou_total_money' => $orderData['caigou_total_money']
    		];
    		return $this->Json(1, '', $res);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }
	/**
     *
     *补退明细
     * @date 2021年3月13日
     *
     */
	public function stallFeedDetail(){
		$mid  = $this->request->param('mid/d', 0);
        $stallsKV = getStallsKV();
		$orderMaterialService = new OrderMaterialService();
		$omInfo=$orderMaterialService->getInfoById($mid, "material_id,fabric_width,weight");
		if(!$omInfo) return $this->error("数据异常");
    	if ($this->request->isAjax() || $this->request->param('export/d', 0)) {

			$materialService = new MaterialService();
			$orderMaterialItemService = new OrderMaterialItemService();
			$clientOrdernum  = $this->request->param('client_ordernum/s');

			$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
			$export     = $this->request->param('export/d', 0);
			$where      = $data = [];

			$where[] = ['order_material_id', '=', $mid];

			$where[] = ['original', '=', 0];

			$order="id desc";
			$data['data'] = db('stall_feed')->where($where)->page($page)->limit($limit)->order($order)->select();

			$data['mInfo']['weight'] = $omInfo['weight'];
			$data['mInfo']['fabric_width'] = $omInfo['fabric_width'];

			foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['caigou_amount']=sprintf("%.2f",$value['billing_caigou_count_feed']*$value['caigou_unitprice']);
				$data['data'][$key]['mInfo'] = $data['mInfo'];
			}

			$data['count'] = db('stall_feed')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}

    	$assign = [
    		'mid' => $mid,
            'stallsKV' => ['0' => '请选择'] + $stallsKV,
    	];
    	return $this->assign($assign)->fetch();
	}
	/**
     * 物料详情
     *
     * @date 2020年11月6日
     *
     */
    public function makeTagLog()
    {
    	$mid  = $this->request->param('mid/d', '');
    	if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
    		$orderMaterialService = new OrderMaterialService();
			$materialService = new MaterialService();
			$orderMaterialItemService = new OrderMaterialItemService();
			$clientOrdernum  = $this->request->param('client_ordernum/s');
			$name  = $this->request->param('name/s','');
			$caigouConfirmTime  = $this->request->param('caigou_confirm_time/s','');
			$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
			$export     = $this->request->param('export/d', 0);
			$where      = $data = [];
			if ($export) {
				set_time_limit(0);
				ini_set('memory_limit', '1024M');
				$page = 1;
				$limit = 99999;
			}
			if($clientOrdernum!=""){
				$where[] = ['client_ordernum', 'like', "%".$clientOrdernum."%"];
			}
			if($name!=""){
				$subQuery = db('material')->where('name', 'like', "%".$name."%")->distinct(true)->field('id')->buildSql();
				$where[] = ['material_name', 'like', "%".$name."%"];
			}
			if($caigouConfirmTime!=""){
				list($startTime, $endTime) = array_map('strtotime', explode('~', $caigouConfirmTime));
				$where[] = ['create_time', 'between', [$startTime, $endTime+86399]];
			}
			if($mid!=""){
				$where[] = ['order_material_id', '=', $mid];
			}
			$order="id desc";
			$omInfo= db('order_material_log')->where($where)->page($page)->limit($limit)->order($order)->select();
			if(!empty($omInfo)){
				foreach ($omInfo as $k => $v) {
                    $v['stalls_name']=arrayGet(getStallsKV(),$v['stalls_id'],'');
                    $v['is_from_stock_name']=$v['is_from_stock']==0? '否':'是';
					$data['data'][]=$v;
				}
			}
			//导出
            if ($export) {
                $this->_exportMakeTagXls('打标日志-' .date('YmdHis'), $data['data']);
                exit;
            }
			$data['count'] = db('order_material_log')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';

    		return json($data);
    	}

    	$assign = [
    		'mid' => $mid
    	];
    	return $this->assign($assign)->fetch();
    }
	/**
	 * 打标日志导出
	 *
	 * @author King
	 * @date 2020年9月22日
	 *
	 */
	private function _exportMakeTagXls($title, &$list) {
		$params = [];
		$data = [];
		foreach ($list as $k => $v) {
			$data[] = [
				$v['client_ordernum'],
				$v['omInfo']['shiji_caigou_count'],
				$v['create_time'] == 0 ? '':date('Y-m-d H:i:s', $v['create_time']),
				$v['mInfo']['name'],
				$v['is_from_stock'],
				$v['stalls_name'],
			];
		}

		$params['file'] = $title;
		$params['sheet'] = [
			[
				'head' => ['订单号','打标条数','打标时间','物料名称','是否库存','档口'], // 表头
				'data' => $data,
			],
		];

		plugins_run('excel/excel/export', $params);
	}
    /**
     * 来料退料记录
     *
     * @author KING
     * @date 2020年7月14日
     *
     */
    public function materialLog()
    {
    	$mid  = $this->request->param('mid/d', 0);
    	if ($this->request->isAjax()) {
    		$orderMaterialService = new OrderMaterialService();
    		$omInfo = $orderMaterialService->getInfoById($mid);
    		$orderId = arrayGet($omInfo, 'order_id', 0);
    		$materialId = arrayGet($omInfo, 'material_id', 0);

    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$offset		= ($page-1) * $limit;

    		$sql = "(SELECT 1 as ct,type,tiaoshu,'' as cloth_num,create_time as time FROM ".config('database.prefix')."order_material_log WHERE order_id={$orderId} AND material_id={$materialId})";
    		$sql .= "UNION All (SELECT 2 as ct,mrl.type,1 as tiaoshu,mr.cloth_num,mrl.create_time FROM ".config('database.prefix')."material_return_log mrl
			LEFT JOIN ".config('database.prefix')."material_return mr ON mrl.material_return_id=mr.id
			WHERE mr.order_id={$orderId} AND mr.material_id={$materialId})";
    		$res = db()->query("SELECT COUNT(*) as num FROM ({$sql}) tb");
    		$data['count'] = $res?$res[0]['num']:0;
    		$list = db()->query("SELECT ct,type,tiaoshu,cloth_num,time FROM ({$sql}) tb ORDER BY time DESC LIMIT {$offset},{$limit}");

    		$data['data'] = $list;
    		$data['code'] = 0;
    		$data['msg'] = '';

    		return json($data);
    	}

    	$assign = [
    		'mid' => $mid
    	];
    	return $this->assign($assign)->fetch();
    }

    /**
     * 开始采购面里料
     *
     *
     * @author KING
     * @date 2020年6月3日
     *
     */
    public function startPurchasing() {
    	$materialId = $this->request->param('material_id/d', 0);
    	$orderId = $this->request->param('order_id/d', 0);

    	db('order_material')->where(['order_id' => $orderId, 'material_id' => $materialId])->update(['is_caigou_start' => 1 ,'caigou_start_time' => time()]);

    	return $this->Json(1);
    }

    /**
     * 获取物料状态
     *
     * @author King
     * @date 2020年10月13日
     *
     */
    public function getMaterialStatus() {
    	$mid = $this->request->param('mid/d', 0);
    	$orderMaterialService = new OrderMaterialService();
    	$stockService = new StockService();
		$stockLogService = new StockLogService();
    	$materialStockUseService = new MaterialStockUseService();
    	$materialStockService = new MaterialStockService();

    	$omInfo = $orderMaterialService->getInfoById($mid);

    	$omInfo['total_material_dosage'] = round(1 * $omInfo['material_dosage'], 2);

    	// 余料使用
    	if (arrayGet($omInfo['mInfo'], 'type') == 'accessories') {
    		$omInfo['stock_use_num'] = $stockLogService->getUseNum($omInfo['material_id'], $omInfo['order_id']);
    	} else {
    		$applyAndUsed = $materialStockUseService->getApplyAndUsed($omInfo['material_id'], $omInfo['order_id']);
    		$metreLeftInfo = $materialStockService->checkMetreLeft($omInfo['material_id']);
    		$omInfo['check_metre_left'] = $metreLeftInfo;
    		$omInfo['apply_and_used'] = $applyAndUsed;
    	}

    	// 采购状态
    	if (arrayGet($omInfo['mInfo'], 'type') == 'accessories') {
    	} else {
    		$omInfo['metre_left'] = $materialStockService->getMetreLeft($omInfo['material_id']);
    	}

    	$omInfo['material_status'] = $orderMaterialService->getMaterialStatus($mid);
    	return $this->Json(1, '', $omInfo);
    }

	public function updateCaichuangCanDo(){
		$orderId = $this->request->param('order_id/d', 0);
		$orderMaterialService=new OrderMaterialService();
		//更新裁剪状态
		$orderMaterialService->updateCaichuangStatus($orderId,0);
		return $this->Json(1);
	}
}
